{"file_path":"src/ReserveManager.sol","creation_status":"success","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {AccessControlUpgradeable} from \"@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol\";\nimport {Initializable} from \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport {UUPSUpgradeable} from \"@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol\";\nimport {PausableUpgradeable} from \"@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol\";\nimport {ReentrancyGuardUpgradeable} from \"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IERC20Metadata} from \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport {IERC4626} from \"@openzeppelin/contracts/interfaces/IERC4626.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\n\nimport {ICascadeBackstop} from \"./interfaces/ICascadeBackstop.sol\";\nimport {ICuratorModule} from \"./interfaces/ICuratorModule.sol\";\nimport {IReserveManager} from \"./interfaces/IReserveManager.sol\";\nimport {IReserveLossAbsorber} from \"./interfaces/IReserveLossAbsorber.sol\";\nimport {IReserveLossGovernor, IReserveLossTimelock} from \"./interfaces/IReserveLossGovernance.sol\";\nimport {IMintRedeemController} from \"./interfaces/IMintRedeemController.sol\";\nimport {IsUSDfr} from \"./interfaces/IsUSDfr.sol\";\nimport {LossEventIds} from \"./libraries/LossEventIds.sol\";\nimport {ReserveCreditLib} from \"./libraries/ReserveCreditLib.sol\";\nimport {ReserveCascadeLib} from \"./libraries/ReserveCascadeLib.sol\";\nimport {ReserveIncidentLib} from \"./libraries/ReserveIncidentLib.sol\";\nimport {ReserveStorageLib} from \"./libraries/ReserveStorageLib.sol\";\nimport {ReserveWiringLib} from \"./libraries/ReserveWiringLib.sol\";\nimport {ReserveAccrualStorageLib} from \"./libraries/ReserveAccrualStorageLib.sol\";\nimport {ReserveMigrationLib} from \"./libraries/ReserveMigrationLib.sol\";\nimport {ReserveMigrationViewLib} from \"./libraries/ReserveMigrationViewLib.sol\";\nimport {IAccrualMigration} from \"./interfaces/IAccrualMigration.sol\";\nimport {ReserveAccrualLib} from \"./libraries/ReserveAccrualLib.sol\";\nimport {ReserveAccrualCreditLib} from \"./libraries/ReserveAccrualCreditLib.sol\";\nimport {ReserveAccrualLifecycleLib} from \"./libraries/ReserveAccrualLifecycleLib.sol\";\nimport {ReserveAccrualServiceLib} from \"./libraries/ReserveAccrualServiceLib.sol\";\nimport {ReserveAccrualViewsLib} from \"./libraries/ReserveAccrualViewsLib.sol\";\nimport {ReserveRoundingLib} from \"./libraries/ReserveRoundingLib.sol\";\nimport {IContinuousAccrual} from \"./interfaces/IContinuousAccrual.sol\";\nimport {IAccrualLifecycle} from \"./interfaces/IAccrualLifecycle.sol\";\nimport {Roles} from \"./libraries/Roles.sol\";\nimport {BorrowerPayoutLib} from \"./libraries/BorrowerPayoutLib.sol\";\n\n/// @title ReserveManager — mainnet-v1 USDC treasury\n/// @notice Custodies canonical USDC and records conservatively marked deployed principal.\n/// @dev Mainnet v1 intentionally has no generic stable registry, reserve instrument, or DSRA.\n///      Unexpected direct USDC transfers are donations and do not increase reported backing,\n///      except when governance attributes physical surplus to a previously written-down custody\n///      incident under that arm's immutable recovery ceiling.\ncontract ReserveManager is\n    Initializable,\n    AccessControlUpgradeable,\n    PausableUpgradeable,\n    ReentrancyGuardUpgradeable,\n    UUPSUpgradeable,\n    IReserveManager\n{\n    using SafeERC20 for IERC20;\n\n    bytes32 private constant _MIXED_INTEREST_VERSION = keccak256(\"forestroad.mixed-interest.v1\");\n\n    /// @dev Native mutations cannot overlap an accrual transition or a guarded host callback.\n    modifier accrualIdle() {\n        _requireNativeIdle();\n        _;\n    }\n\n    /// @dev THE STORAGE STRUCT STAYS DECLARED HERE, DELIBERATELY, even though the EIP-170\n    ///      extraction moved every credit-path BODY into `ReserveCreditLib`. Moving the struct\n    ///      into a library would be layout-identical, but the storage-layout gates key on the\n    ///      declaring file, so they would read it as a REMOVAL and demand `--allow-removals`, a\n    ///      flag whose documented meaning is \"this proxy is being freshly redeployed\". It is not:\n    ///      this is a live mainnet proxy. Leaving the declaration in place keeps the change\n    ///      layout-neutral BY CONSTRUCTION rather than by argument, and keeps both baselines and\n    ///      the compiler-backed probe pointing at the same key they have always pointed at. The\n    ///      libraries take `ReserveManager.ReserveStorage storage` and the resulting circular\n    ///      import is a type-only reference, which solc resolves without embedding any code.\n    /// @custom:storage-location erc7201:forestroad.storage.ReserveManager\n    struct ReserveStorage {\n        IERC20 usdcToken;\n        uint256 idleUSDCUnits;\n        uint256 totalDeployedPrincipal;\n        mapping(uint256 facilityId => uint256) deployed;\n        // Deprecated C-01 v1 hook. Reserved forever for upgrade-layout compatibility.\n        IReserveLossAbsorber lossAbsorber;\n        // C-01 remediation tail: the independent supply/backing source and the governance-opened\n        // custody-incident state. Facility ids occupy the lower uint256 half; incident ids the upper.\n        IMintRedeemController lossController;\n        uint256 activeReserveLossIncidentId;\n        bytes32 activeReserveLossEvidenceHash;\n        uint256 reserveDeficit;\n        mapping(uint256 incidentId => bool) reserveLossIncidentUsed;\n        // C-01 ADR-0033 append-only orchestration tail.\n        ICuratorModule lossCurator;\n        ICascadeBackstop lossBackstop;\n        IsUSDfr lossVault;\n        IERC20 lossUSDfr;\n        address lossGovernor;\n        address lossTimelock;\n        uint256 recognizedBackingReduction;\n        uint256 recognizedSurplusAbsorbed;\n        uint256 recognizedSupplyReduction;\n        uint256 reserveLossPreArmExpiry;\n        bytes32 reserveLossPreArmEvidenceHash;\n        bytes32 reserveLossPreArmTimingHash;\n        bool reserveLossPreArmDegraded;\n        bool guardianReserveLossArmsEnabled;\n        // Deprecated pre-arm fields above remain reserved forever. The persistent state machine\n        // is append-only so an upgrade cannot reinterpret an expiry/timing latch as an arm id.\n        uint256 nextReserveLossArmId;\n        uint256 activeReserveLossArmId;\n        bytes32 activeReserveLossArmEvidenceHash;\n        mapping(uint256 armId => uint256 nativeUnits) reserveLossRecoveryCapacityUnits;\n        // G3: append-only conservative marks on deployed facility principal.\n        // Each facility mark is bounded by its live face, so the aggregate can never exceed\n        // totalDeployedPrincipal and the checked subtraction in `_backingValue` cannot underflow.\n        uint256 totalPrincipalImpairment;\n        mapping(uint256 facilityId => uint256) principalImpairment;\n        // ADR-0034 Y-bis compatibility tail. This ledger is independent of the custody-loss\n        // arm state machine and is consumed only by the wired loss absorber.\n        uint256 exitPrepaidAbsorption;\n    }\n\n    /// @dev The ERC-7201 root of the LIVE implementation. Changing this bricks the proxy.\n    bytes32 internal constant RESERVE_STORAGE_LOCATION =\n        0xc49ad79e2b58679c441432bede06c67f7802343349e70ccf00d8d1ce92bb1b00;\n\n    /// @custom:oz-upgrades-unsafe-allow constructor\n    constructor() {\n        _disableInitializers();\n    }\n\n    /// @notice Initializes the reserve roles and canonical six-decimal USDC custody token.\n    function initialize(address admin, address reserveAdmin, address guardian, address upgrader, address usdc_)\n        external\n        initializer\n    {\n        if (\n            admin == address(0) || reserveAdmin == address(0) || guardian == address(0) || upgrader == address(0)\n                || usdc_ == address(0)\n        ) revert ReserveManager_ZeroAddress();\n        uint8 decimals = IERC20Metadata(usdc_).decimals();\n        if (decimals != 6) revert ReserveManager_InvalidUSDCDecimals(decimals);\n        __AccessControl_init();\n        __Pausable_init();\n        __ReentrancyGuard_init();\n        __UUPSUpgradeable_init();\n        _grantRole(DEFAULT_ADMIN_ROLE, admin);\n        _grantRole(Roles.RESERVE_ADMIN_ROLE, reserveAdmin);\n        _grantRole(Roles.GUARDIAN_ROLE, guardian);\n        _grantRole(Roles.UPGRADER_ROLE, upgrader);\n        ReserveStorage storage $ = _storage();\n        $.usdcToken = IERC20(usdc_);\n        $.guardianReserveLossArmsEnabled = true;\n    }\n\n    /// @inheritdoc IReserveManager\n    function setBorrowerPayoutRegistry(address registry) external accrualIdle onlyRole(DEFAULT_ADMIN_ROLE) {\n        // The library returns the bound address only to keep the delegatecall compact. Binding\n        // either validates, stores and emits, or reverts; the host has no second value to check.\n        BorrowerPayoutLib.bind(registry);\n    }\n\n    /// @inheritdoc IReserveManager\n    function borrowerPayoutRegistry() external view returns (address) {\n        return BorrowerPayoutLib.registry();\n    }\n\n    /// @inheritdoc IReserveManager\n    function depositUSDC(address from, uint256 amount)\n        external\n        accrualIdle\n        nonReentrant\n        whenNotPaused\n        returns (uint256 credited)\n    {\n        if (!hasRole(Roles.CONTROLLER_ROLE, msg.sender) && !hasRole(Roles.CREDIT_ROLE, msg.sender)) {\n            revert ReserveManager_NotDepositor(msg.sender);\n        }\n        if (from == address(0)) revert ReserveManager_ZeroAddress();\n        if (amount == 0) revert ReserveManager_ZeroAmount();\n        ReserveStorage storage $ = _storage();\n        uint256 beforeBalance = $.usdcToken.balanceOf(address(this));\n        $.usdcToken.safeTransferFrom(from, address(this), amount);\n        uint256 received = $.usdcToken.balanceOf(address(this)) - beforeBalance;\n        if (received == 0) revert ReserveManager_NoValueReceived();\n        if (received != amount) revert ReserveManager_UnexpectedUSDCReceipt(amount, received);\n        $.idleUSDCUnits += received;\n        credited = ReserveStorageLib.normalize(received);\n        emit USDCDeposited(from, amount, credited);\n    }\n\n    /// @inheritdoc IReserveManager\n    function releaseUSDC(address to, uint256 amount)\n        external\n        accrualIdle\n        onlyRole(Roles.CONTROLLER_ROLE)\n        nonReentrant\n        whenNotPaused\n    {\n        _release(to, amount);\n    }\n\n    /// @inheritdoc IReserveManager\n    /// @dev The lock is derived directly from the same canonical balance, so observation is\n    ///      reversible and permissionless without giving the caller authority to create state.\n    function reconcileIdleUSDC() external accrualIdle nonReentrant returns (uint256 shortfall) {\n        ReserveStorage storage $ = _storage();\n        uint256 live = $.usdcToken.balanceOf(address(this));\n        uint256 recorded = $.idleUSDCUnits;\n        shortfall = recorded > live ? recorded - live : 0;\n        emit IdleUSDCObserved(recorded, live, shortfall);\n    }\n\n    /// @notice Permanently disabled tombstone for the archived arbitrary idle-write-down path.\n    /// @dev Archived arbitrary-loss entry point is intentionally disabled. New loss accounting\n    ///      binds an arm, rederives the canonical shortfall and enforces the voted ceiling.\n    function writeDownIdleUSDC(uint256) external pure {\n        revert ReserveManager_LegacyPathDisabled();\n    }\n\n    /// @dev ABI tombstone for archived tests and pre-remediation operator tooling. The arbitrary\n    ///      amount path is intentionally uncallable: all new loss accounting must bind an arm,\n    ///      rederive the canonical shortfall and enforce the voted ceiling in `ratifyAndOpen`.\n    /// @inheritdoc IReserveManager\n    function observeIdleUSDC() external view returns (uint256 recorded, uint256 live, uint256 shortfall) {\n        ReserveStorage storage $ = _storage();\n        recorded = $.idleUSDCUnits;\n        live = $.usdcToken.balanceOf(address(this));\n        shortfall = recorded > live ? recorded - live : 0;\n    }\n\n    /// @notice Compatibility alias for the live custody limb retained by the merged cascade.\n    function idleCustodyShortfall() public view returns (uint256) {\n        uint256 shortfall = _liveShortfallUnits(_storage());\n        return ReserveStorageLib.normalize(shortfall);\n    }\n\n    /// @notice Conservative backing after subtracting the physically observed custody gap.\n    function recognizedBackingValue() external view returns (uint256) {\n        return ReserveAccrualViewsLib.backing(_storage(), true);\n    }\n\n    /// @notice Compatibility binding retained for the ADR-0034 loss absorber. It is not a\n    /// credit path; custody recovery remains exclusively arm-bound `creditRecoveredIdleUSDC`.\n    function setLossAbsorber(address absorber) external accrualIdle onlyRole(DEFAULT_ADMIN_ROLE) {\n        ReserveWiringLib.bindAbsorber(_storage(), absorber);\n    }\n\n    /// @notice Legacy incident opener retained for pre-arm audit harnesses. It does not move\n    /// backing or credit custody; new production loss accounting must use armReserveLossFreeze\n    /// followed by ratifyAndOpen.\n    function openReserveLossIncident(uint256 incidentNonce, bytes32 evidenceHash)\n        external\n        accrualIdle\n        onlyRole(DEFAULT_ADMIN_ROLE)\n        returns (uint256 incidentId)\n    {\n        return ReserveIncidentLib.openIncident(_storage(), incidentNonce, evidenceHash);\n    }\n\n    /// @inheritdoc IReserveManager\n    function closeReserveLossIncident(uint256 incidentId) external accrualIdle onlyRole(DEFAULT_ADMIN_ROLE) {\n        ReserveIncidentLib.closeIncident(_storage(), incidentId);\n    }\n\n    /// @inheritdoc IReserveManager\n    function resolveReserveDeficit(bytes32 evidenceHash) external accrualIdle onlyRole(DEFAULT_ADMIN_ROLE) {\n        ReserveIncidentLib.resolveDeficit(_storage(), evidenceHash);\n    }\n\n    /// @inheritdoc IReserveManager\n    function unrecordedUSDC() external view returns (uint256) {\n        ReserveStorage storage $ = _storage();\n        uint256 live = $.usdcToken.balanceOf(address(this));\n        return live > $.idleUSDCUnits ? live - $.idleUSDCUnits : 0;\n    }\n\n    /// @dev ABI tombstone for the superseded pre-existing-surplus credit route. The merged\n    ///      production path is exclusively `creditRecoveredIdleUSDC(armId,evidenceHash)`.\n    /// @inheritdoc IReserveManager\n    function setLossController(address controller_) external accrualIdle onlyRole(DEFAULT_ADMIN_ROLE) {\n        ReserveWiringLib.bindController(_storage(), controller_);\n    }\n\n    /// @inheritdoc IReserveManager\n    function setReserveLossModules(address curator, address backstop, address vault, address governor, address timelock)\n        external\n        accrualIdle\n        onlyRole(DEFAULT_ADMIN_ROLE)\n    {\n        ReserveWiringLib.bindModules(_storage(), curator, backstop, vault, governor, timelock);\n    }\n\n    /// @inheritdoc IReserveManager\n    function armReserveLossFreeze(bytes32 evidenceHash)\n        external\n        accrualIdle\n        onlyRole(Roles.GUARDIAN_ROLE)\n        returns (uint256 armId, uint256 incidentId)\n    {\n        return ReserveIncidentLib.arm(_storage(), evidenceHash);\n    }\n\n    /// @inheritdoc IReserveManager\n    function cancelAndDisable(uint256 expectedArmId, bytes32 evidenceHash)\n        external\n        accrualIdle\n        onlyRole(DEFAULT_ADMIN_ROLE)\n    {\n        ReserveIncidentLib.cancel(_storage(), expectedArmId, evidenceHash);\n    }\n\n    /// @inheritdoc IReserveManager\n    function cancelUnratifiedArm(uint256 expectedArmId, bytes32 evidenceHash)\n        external\n        accrualIdle\n        onlyRole(DEFAULT_ADMIN_ROLE)\n    {\n        ReserveIncidentLib.cancelUnratified(_storage(), expectedArmId, evidenceHash);\n    }\n\n    /// @inheritdoc IReserveManager\n    function setGuardianReserveLossArmsEnabled(bool enabled) external accrualIdle onlyRole(DEFAULT_ADMIN_ROLE) {\n        ReserveStorage storage $ = _storage();\n        $.guardianReserveLossArmsEnabled = enabled;\n        emit GuardianReserveLossArmsEnabled(enabled);\n    }\n\n    /// @inheritdoc IReserveManager\n    function ratifyAndOpen(uint256 expectedArmId, bytes32 evidenceHash, uint256 approvedMaxLoss)\n        external\n        accrualIdle\n        nonReentrant\n        returns (uint256 incidentId, uint256 actualLoss)\n    {\n        _requireReserveLossAdmin();\n        ReserveStorage storage $ = _storage();\n        uint256 armId = _requireActiveArm($, expectedArmId);\n        bytes32 armedEvidenceHash = $.activeReserveLossArmEvidenceHash;\n        if (evidenceHash != armedEvidenceHash) {\n            revert ReserveManager_ArmEvidenceMismatch(armedEvidenceHash, evidenceHash);\n        }\n        uint256 shortfallUnits = _liveShortfallUnits($);\n        if (shortfallUnits == 0) revert ReserveManager_ShortfallCured();\n        actualLoss = ReserveStorageLib.normalize(shortfallUnits);\n        if (actualLoss > approvedMaxLoss) {\n            revert ReserveManager_LossExceedsApproval(actualLoss, approvedMaxLoss);\n        }\n\n        incidentId = LossEventIds.custodyEventId(armId);\n        assert(LossEventIds.isCustodyEvent(incidentId));\n        uint256 active = $.activeReserveLossIncidentId;\n        if (active == 0) {\n            if ($.reserveLossIncidentUsed[incidentId]) revert ReserveManager_IncidentAlreadyUsed(incidentId);\n            $.reserveLossIncidentUsed[incidentId] = true;\n            $.activeReserveLossIncidentId = incidentId;\n            emit ReserveLossIncidentOpened(incidentId, armId, evidenceHash);\n        } else if (active != incidentId) {\n            revert ReserveManager_IncidentMismatch(active, incidentId);\n        }\n        $.activeReserveLossEvidenceHash = evidenceHash;\n        $.reserveLossRecoveryCapacityUnits[armId] += shortfallUnits;\n\n        ReserveAccrualLib.prepareNativeLoss($);\n        ReserveCascadeLib.recognize($, shortfallUnits, actualLoss);\n        if ($.recognizedSupplyReduction != 0) ReserveCascadeLib.absorb($, incidentId);\n        emit IdleUSDCWrittenDown(actualLoss, ReserveStorageLib.normalize($.idleUSDCUnits));\n        emit ReserveLossRatified(armId, incidentId, approvedMaxLoss, actualLoss, evidenceHash);\n    }\n\n    /// @inheritdoc IReserveManager\n    function creditRecoveredIdleUSDC(uint256 armId, bytes32 evidenceHash)\n        external\n        accrualIdle\n        nonReentrant\n        returns (uint256 credited)\n    {\n        _requireReserveLossAdmin();\n        return ReserveIncidentLib.creditRecovery(_storage(), armId, evidenceHash);\n    }\n\n    /// @inheritdoc IReserveManager\n    function finalizeAndDisable(uint256 expectedArmId, bytes32 evidenceHash)\n        external\n        accrualIdle\n        onlyRole(DEFAULT_ADMIN_ROLE)\n    {\n        ReserveIncidentLib.finalize(_storage(), expectedArmId, evidenceHash);\n    }\n\n    /// @inheritdoc IReserveManager\n    function recordDeployment(uint256 facilityId, address to, uint256 usdcAmount)\n        external\n        accrualIdle\n        onlyRole(Roles.CREDIT_ROLE)\n        nonReentrant\n        whenNotPaused\n    {\n        ReserveAccrualCreditLib.requireUnregisteredFunding(facilityId);\n        ReserveCreditLib.deploy(_storage(), facilityId, to, usdcAmount);\n    }\n\n    /// @inheritdoc IReserveManager\n    function recordFeeCapitalization(uint256 facilityId, uint256 amount)\n        external\n        accrualIdle\n        onlyRole(Roles.CREDIT_ROLE)\n        whenNotPaused\n    {\n        ReserveAccrualCreditLib.requireUnregisteredFunding(facilityId);\n        ReserveCreditLib.capitalize(_storage(), facilityId, amount, true);\n    }\n\n    /// @inheritdoc IReserveManager\n    /// @dev THE TWIN OF `recordFeeCapitalization`, sharing its body, and the ONLY difference is the\n    ///      idle-value check. The fee twin is sound because the fee's cash NEVER LEFT: `fund`\n    ///      deploys `principal - fee`, so backing rises against RETAINED CASH and bounding it by\n    ///      idle is meaningful. There is no retained cash behind a PIK capitalisation; what stands\n    ///      behind it is the borrower's obligation to repay a larger balance and, beneath that, the\n    ///      curator first-loss layer. Bounding a receivable by idle cash would refuse a legitimate\n    ///      capitalisation on a drawn-down book and admit one on a flush book.\n    ///\n    ///      EVERY OTHER BOUND LIVES IN `WaterfallEngine.capitalizePik`. Do not call this from\n    ///      anywhere that does not carry them.\n    function recordPikCapitalization(uint256 facilityId, uint256 amount)\n        external\n        accrualIdle\n        onlyRole(Roles.CREDIT_ROLE)\n        whenNotPaused\n    {\n        ReserveAccrualCreditLib.requireLegacy(facilityId);\n        ReserveCreditLib.capitalize(_storage(), facilityId, amount, false);\n    }\n\n    /// @inheritdoc IReserveManager\n    function recordPayment(uint256 facilityId, address payer, uint256 usdcAmount, uint256 principal)\n        external\n        accrualIdle\n        onlyRole(Roles.CREDIT_ROLE)\n        nonReentrant\n        whenNotPaused\n        returns (uint256 receivedValue)\n    {\n        ReserveAccrualCreditLib.requireLegacy(facilityId);\n        receivedValue = ReserveCreditLib.pay(_storage(), facilityId, payer, usdcAmount, principal);\n    }\n\n    /// @inheritdoc IReserveManager\n    function recordPrincipalWritedown(uint256 facilityId, uint256 amount)\n        external\n        accrualIdle\n        onlyRole(Roles.CREDIT_ROLE)\n    {\n        if (ReserveAccrualStorageLib.state().enabled) ReserveAccrualLifecycleLib.writeDown(facilityId, amount);\n        ReserveCreditLib.writeDown(_storage(), facilityId, amount);\n    }\n\n    /// @inheritdoc IReserveManager\n    /// @dev This is a valuation transition, not a cascade transition: it moves no value and\n    ///      burns no claims. Keeping it separate ensures an honest conservative mark is never\n    ///      conditional on the three loss layers having enough immediately burnable capital.\n    function recognizePrincipalImpairment(uint256 facilityId, uint256 amount, bytes32 evidenceHash)\n        external\n        accrualIdle\n        onlyRole(DEFAULT_ADMIN_ROLE)\n    {\n        if (amount == 0) revert ReserveManager_ZeroAmount();\n        if (evidenceHash == bytes32(0)) revert ReserveManager_ZeroEvidenceHash();\n        ReserveStorage storage $ = _storage();\n        // A valuation must cover earned receivables as well as previously recorded face.\n        if (ReserveAccrualStorageLib.state().enabled) ReserveAccrualCreditLib.post($, facilityId);\n        uint256 recognized = $.principalImpairment[facilityId];\n        uint256 face = $.deployed[facilityId];\n        if (amount > face - recognized) {\n            revert ReserveManager_ImpairmentExceedsFace(facilityId, amount, face - recognized);\n        }\n        uint256 facilityImpairment = recognized + amount;\n        $.principalImpairment[facilityId] = facilityImpairment;\n        uint256 total = $.totalPrincipalImpairment + amount;\n        $.totalPrincipalImpairment = total;\n        emit PrincipalImpairmentRecognized(\n            facilityId, amount, facilityImpairment, total, _backingValue($), evidenceHash\n        );\n    }\n\n    /// @inheritdoc IReserveManager\n    function releasePrincipalImpairment(uint256 facilityId, uint256 amount, bytes32 evidenceHash)\n        external\n        accrualIdle\n        onlyRole(DEFAULT_ADMIN_ROLE)\n    {\n        if (amount == 0) revert ReserveManager_ZeroAmount();\n        if (evidenceHash == bytes32(0)) revert ReserveManager_ZeroEvidenceHash();\n        ReserveStorage storage $ = _storage();\n        uint256 recognized = $.principalImpairment[facilityId];\n        if (amount > recognized) {\n            revert ReserveManager_ImpairmentReleaseExceedsRecognized(facilityId, amount, recognized);\n        }\n        uint256 facilityImpairment = recognized - amount;\n        $.principalImpairment[facilityId] = facilityImpairment;\n        uint256 total = $.totalPrincipalImpairment - amount;\n        $.totalPrincipalImpairment = total;\n        emit PrincipalImpairmentReleased(facilityId, amount, facilityImpairment, total, evidenceHash);\n    }\n\n    /// @notice Pauses routine reserve deposits, releases, deployments, and payments.\n    function pause() external accrualIdle onlyRole(Roles.GUARDIAN_ROLE) {\n        _pause();\n    }\n\n    /// @notice Resumes routine reserve deposits, releases, deployments, and payments.\n    function unpause() external accrualIdle onlyRole(Roles.GUARDIAN_ROLE) {\n        _unpause();\n    }\n\n    /// @inheritdoc IReserveManager\n    function idleReserve() external view returns (uint256) {\n        return ReserveStorageLib.normalize(_storage().idleUSDCUnits);\n    }\n\n    /// @inheritdoc IReserveManager\n    function idleUSDC() external view returns (uint256) {\n        return _storage().idleUSDCUnits;\n    }\n\n    /// @inheritdoc IReserveManager\n    function deployedPrincipal() external view returns (uint256) {\n        return ReserveAccrualViewsLib.deployed(_storage(), 0, true);\n    }\n\n    /// @inheritdoc IReserveManager\n    function totalBackingValue() external view returns (uint256) {\n        return ReserveAccrualViewsLib.backing(_storage(), false);\n    }\n\n    /// @inheritdoc IReserveManager\n    function totalPrincipalImpairment() external view returns (uint256) {\n        return _storage().totalPrincipalImpairment;\n    }\n\n    /// @inheritdoc IReserveManager\n    function principalImpairmentOf(uint256 facilityId) external view returns (uint256) {\n        return _storage().principalImpairment[facilityId];\n    }\n\n    /// @inheritdoc IReserveManager\n    function deployedTo(uint256 facilityId) external view returns (uint256) {\n        return ReserveAccrualViewsLib.deployed(_storage(), facilityId, false);\n    }\n\n    /// @notice Pulls exact USDC from a recapitalizing funder and records only what arrived.\n    ///         This cannot credit pre-existing surplus; that remains arm-bound recovery.\n    function recapitalize(uint256 amount) external accrualIdle nonReentrant returns (uint256 credited) {\n        if (amount == 0) revert ReserveManager_ZeroAmount();\n        ReserveStorage storage $ = _storage();\n        uint256 beforeBalance = $.usdcToken.balanceOf(address(this));\n        $.usdcToken.safeTransferFrom(msg.sender, address(this), amount);\n        uint256 received = $.usdcToken.balanceOf(address(this)) - beforeBalance;\n        if (received == 0) revert ReserveManager_NoValueReceived();\n        if (received != amount) revert ReserveManager_UnexpectedUSDCReceipt(amount, received);\n        $.idleUSDCUnits += received;\n        credited = ReserveStorageLib.normalize(received);\n        emit Recapitalized(msg.sender, received, credited, _backingValue($), $.reserveDeficit);\n    }\n\n    /// @notice Compatibility view for the historical exit-prepayment cascade ledger.\n    function exitPrepaidAbsorption() external view returns (uint256) {\n        return _storage().exitPrepaidAbsorption;\n    }\n\n    /// @inheritdoc IReserveManager\n    function recordExitPrepayment(uint256 amount) external accrualIdle {\n        ReserveStorage storage $ = _storage();\n        if (msg.sender != address($.lossAbsorber)) revert ReserveManager_NotLossAbsorber(msg.sender);\n        if (amount == 0) revert ReserveManager_ZeroAmount();\n        uint256 outstanding = $.exitPrepaidAbsorption + amount;\n        $.exitPrepaidAbsorption = outstanding;\n        emit ExitPrepaymentRecorded(amount, outstanding);\n    }\n\n    /// @inheritdoc IReserveManager\n    function consumeExitPrepayment(uint256 facilityId, uint256 loss) external accrualIdle returns (uint256 used) {\n        ReserveStorage storage $ = _storage();\n        if (msg.sender != address($.lossAbsorber)) revert ReserveManager_NotLossAbsorber(msg.sender);\n        uint256 prepaid = $.exitPrepaidAbsorption;\n        if (prepaid == 0) return 0;\n        uint256 releasable = $.principalImpairment[facilityId];\n        if (releasable > loss) releasable = loss;\n        used = prepaid < releasable ? prepaid : releasable;\n        if (used == 0) return 0;\n        uint256 outstanding = prepaid - used;\n        $.exitPrepaidAbsorption = outstanding;\n        emit ExitPrepaymentConsumed(facilityId, used, outstanding);\n    }\n\n    /// @notice Configures immutable counterparties before all modules bind and recognition starts.\n    function configureContinuousAccrual(IContinuousAccrual.Modules calldata modules_)\n        external\n        onlyRole(DEFAULT_ADMIN_ROLE)\n        nonReentrant\n    {\n        ReserveAccrualLib.configure(_storage(), modules_);\n    }\n\n    /// @inheritdoc IReserveManager\n    function requireLegacyRollbackSafe() external view accrualIdle {\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        if (s.enabled || s.migration.active || s.recordedFace != 0 || s.roundingUnabsorbed != 0) {\n            revert ReserveManager_LegacyRollbackUnsafe();\n        }\n    }\n\n    /// @notice Starts prospective recognition after compatible consumer bindings are verified.\n    function enableContinuousAccrual() external onlyRole(DEFAULT_ADMIN_ROLE) nonReentrant {\n        ReserveAccrualLib.enable(_storage());\n    }\n\n    /// @notice The bound bridge atomically enables admission of authenticated mixed facilities.\n    function enableMixedInterest() external nonReentrant {\n        ReserveAccrualLib.enableMixedInterest();\n    }\n\n    function mixedInterestEnabled() external view returns (bool) {\n        return ReserveAccrualStorageLib.state().mixedInterestEnabled;\n    }\n\n    /// @notice Exact cross-module version used by activation and downgrade checks.\n    function mixedInterestVersion() external pure returns (bytes32) {\n        return _MIXED_INTEREST_VERSION;\n    }\n\n    /// @notice Executes one governed opening-import preparation step.\n    /// @dev The complete step encoding is defined by IAccrualMigration.\n    function prepareContinuousAccrualMigration(bytes calldata step)\n        external\n        onlyRole(DEFAULT_ADMIN_ROLE)\n        nonReentrant\n    {\n        ReserveMigrationLib.prepare(_storage(), step);\n    }\n\n    /// @notice Constant-time status for the frozen roster; a partial book is never quoted here.\n    function accrualMigration() external view returns (IAccrualMigration.Progress memory) {\n        _returnEncodedView(ReserveMigrationViewLib.progressData());\n    }\n\n    /// @notice The bound waterfall synchronizes its fee rate and destination prospectively.\n    function setAccrualFee(uint16 feeBps, address recipient) external nonReentrant {\n        ReserveAccrualLib.setFee(_storage(), feeBps, recipient);\n    }\n\n    /// @notice The cumulative part of proved sub-unit losses for which native capital was unavailable.\n    function roundingLossUnabsorbed() external view returns (uint256) {\n        return ReserveAccrualStorageLib.state().roundingUnabsorbed;\n    }\n\n    /// @notice Consumes only the controller's exact current rounding-burn continuation.\n    /// @dev Deliberately inside the outer reserve guard; the library authenticates its single caller.\n    function consumeAccrualLossBurn(address caller, address from, uint256 amount) external returns (bool) {\n        return ReserveRoundingLib.consumeBurn(caller, from, amount);\n    }\n\n    /// @notice Module identities for this independently backed reserve instance.\n    function accrualModules() external view returns (IContinuousAccrual.Modules memory) {\n        _returnEncodedView(ReserveAccrualLib.modulesData());\n    }\n\n    /// @notice Constant-time effective recognition and outstanding posting/issuance claims.\n    function accrualSnapshot() external view returns (IContinuousAccrual.Snapshot memory) {\n        _returnEncodedView(ReserveAccrualLib.snapshotData());\n    }\n\n    /// @notice Current exact delivery permit and coherent accounting prices, or inactive zeros.\n    function accrualDelivery() external view returns (IContinuousAccrual.Delivery memory) {\n        _returnEncodedView(ReserveAccrualLib.deliveryData());\n    }\n\n    /// @notice Authoritative admission gate for every price-sensitive consumer.\n    function requireAccrualFresh() external view {\n        ReserveAccrualLib.requireFresh();\n    }\n\n    /// @notice Converts selected accrued senior/fee claims into physical USDfr, including while paused.\n    function materializeAccrued(uint8 legs) external nonReentrant returns (uint256 senior, uint256 fee) {\n        return ReserveAccrualLib.materialize(_storage(), legs);\n    }\n\n    /// @notice Clock-independent callback admission used by bound accounting consumers.\n    function requireAccrualIdle() external view {\n        ReserveAccrualLib.requireIdle();\n    }\n\n    /// @notice Unposted earned exposure by total, class, borrower or state; reads no facility list.\n    function accrualExposure(uint8 kind, bytes32 identity) external view returns (uint256) {\n        return ReserveAccrualCreditLib.exposure(kind, identity);\n    }\n\n    /// @notice Additional maximum future face already reserved by funded contractual schedules.\n    function accrualReservedExposure() external view returns (uint256) {\n        return ReserveAccrualCreditLib.reservedExposure();\n    }\n\n    /// @notice The bound waterfall registers its authenticated just-funded facility.\n    function registerAccruingLoan(uint256 facilityId) external nonReentrant {\n        ReserveAccrualCreditLib.register(_storage(), facilityId);\n    }\n\n    /// @notice Permissionless chronological maintenance; at most 32 due events per transaction.\n    function checkpointAccrual(uint256 maximum) external nonReentrant returns (uint256 processed, bool fresh) {\n        return ReserveAccrualCreditLib.checkpoint(_storage(), maximum);\n    }\n\n    /// @notice Advances only zero-work contractual PIK dates in constant time.\n    function serviceAccruedLoan(uint256 facilityId) external nonReentrant returns (uint256 capitalized) {\n        return ReserveAccrualServiceLib.service(_storage(), facilityId);\n    }\n\n    /// @notice Discloses whether a known facility has a positive queued accrual segment.\n    function accrualLoanScheduled(uint256 facilityId) external view returns (bool) {\n        return ReserveAccrualServiceLib.scheduled(facilityId);\n    }\n\n    /// @notice Posts a single existing virtual receivable before a native impairment or lifecycle act.\n    function postAccruedLoan(uint256 facilityId) external nonReentrant returns (uint256 amount) {\n        return ReserveAccrualCreditLib.post(_storage(), facilityId);\n    }\n\n    /// @notice The bound waterfall delivers an exact attested repayment of an existing streamed claim.\n    function repayAccruingLoan(uint256 facilityId, address payer, uint256 principal, uint256 interest)\n        external\n        nonReentrant\n        whenNotPaused\n        returns (uint256 outstanding)\n    {\n        return ReserveAccrualLifecycleLib.repay(_storage(), facilityId, payer, principal, interest);\n    }\n\n    /// @notice Releases the finite active-book slot after full repayment/loss and all native risk hooks.\n    function retireAccruedLoan(uint256 facilityId) external nonReentrant {\n        ReserveAccrualLifecycleLib.retire(_storage(), facilityId);\n    }\n\n    /// @notice The bridge forwards a consumed signed amendment, effective only from this block.\n    function amendAccruingLoan(uint256 facilityId, IAccrualLifecycle.Terms calldata terms) external nonReentrant {\n        ReserveAccrualLifecycleLib.amend(_storage(), facilityId, terms);\n    }\n\n    /// @notice The bridge forwards one consumed amendment covering both prospective interest legs.\n    function amendMixedAccruingLoan(uint256 facilityId, IAccrualLifecycle.MixedTerms calldata terms)\n        external\n        nonReentrant\n    {\n        ReserveAccrualLifecycleLib.amendMixed(_storage(), facilityId, terms);\n    }\n\n    /// @notice The bound default manager closes the full earned claim before declaring default.\n    function stopAccruingLoan(uint256 facilityId) external nonReentrant {\n        ReserveAccrualLifecycleLib.stop(_storage(), facilityId);\n    }\n\n    /// @notice The default manager controls growing past-due cohort membership.\n    function setAccrualPastDue(uint256 facilityId, bool marked) external nonReentrant {\n        ReserveAccrualLifecycleLib.setPastDue(facilityId, marked);\n    }\n\n    /// @notice Canonical debt disclosure; reserve backing continues to use its streamed carrier.\n    function accruedDebt(uint256 facilityId) external view returns (IAccrualLifecycle.Debt memory) {\n        _returnEncodedView(ReserveAccrualViewsLib.debt(facilityId));\n    }\n\n    /// @notice Current unpaid interest split by the exact cash-pay and PIK settlement legs.\n    function accruedInterestLegs(uint256 facilityId) external view returns (IAccrualLifecycle.InterestLegs memory) {\n        _returnEncodedView(ReserveAccrualViewsLib.interestLegs(facilityId));\n    }\n\n    /// @notice Unposted growth in the default manager's marked cohort of one class.\n    function accruedPastDue(uint256 classId) external view returns (uint256 amount) {\n        return ReserveAccrualCreditLib.pastDue(classId);\n    }\n\n    /// @notice Facility contribution to the reserve's virtual receivable carrier.\n    function unpostedAccruedLoan(uint256 facilityId) external view returns (uint256 amount) {\n        return ReserveAccrualViewsLib.unpostedLoan(facilityId);\n    }\n\n    /// @inheritdoc IReserveManager\n    function usdc() external view returns (address) {\n        return address(_storage().usdcToken);\n    }\n\n    /// @inheritdoc IReserveManager\n    function lossAbsorber() external view returns (address) {\n        return address(_storage().lossAbsorber);\n    }\n\n    /// @inheritdoc IReserveManager\n    function lossController() external view returns (address) {\n        return address(_storage().lossController);\n    }\n\n    /// @inheritdoc IReserveManager\n    function reserveLossModules()\n        external\n        view\n        returns (address curator, address backstop, address vault, address governor, address timelock)\n    {\n        ReserveStorage storage $ = _storage();\n        return (address($.lossCurator), address($.lossBackstop), address($.lossVault), $.lossGovernor, $.lossTimelock);\n    }\n\n    /// @inheritdoc IReserveManager\n    function activeReserveLossIncident() external view returns (uint256 incidentId, bytes32 evidenceHash) {\n        ReserveStorage storage $ = _storage();\n        return ($.activeReserveLossIncidentId, $.activeReserveLossEvidenceHash);\n    }\n\n    /// @inheritdoc IReserveManager\n    function reserveLossIncidentUsed(uint256 incidentId) external view returns (bool) {\n        return _storage().reserveLossIncidentUsed[incidentId];\n    }\n\n    /// @inheritdoc IReserveManager\n    function reserveDeficit() external view returns (uint256) {\n        return _storage().reserveDeficit;\n    }\n\n    /// @inheritdoc IReserveManager\n    function recognizedReserveLoss()\n        external\n        view\n        returns (uint256 backingReduction, uint256 surplusAbsorbed, uint256 supplyReductionRequired)\n    {\n        ReserveStorage storage $ = _storage();\n        return ($.recognizedBackingReduction, $.recognizedSurplusAbsorbed, $.recognizedSupplyReduction);\n    }\n\n    /// @inheritdoc IReserveManager\n    function reserveLossArm()\n        external\n        view\n        returns (uint256 armId, uint256 incidentId, bytes32 evidenceHash, bool armsEnabled)\n    {\n        ReserveStorage storage $ = _storage();\n        armId = $.activeReserveLossArmId;\n        incidentId = armId == 0 ? 0 : LossEventIds.custodyEventId(armId);\n        return (armId, incidentId, $.activeReserveLossArmEvidenceHash, $.guardianReserveLossArmsEnabled);\n    }\n\n    /// @inheritdoc IReserveManager\n    function reserveLossRecoveryCapacity(uint256 armId) external view returns (uint256 nativeUnits) {\n        return _storage().reserveLossRecoveryCapacityUnits[armId];\n    }\n\n    /// @inheritdoc IReserveManager\n    function reserveLossExitsLocked() external view returns (bool) {\n        return _reserveLossExitsLocked(_storage());\n    }\n\n    /// @inheritdoc IReserveManager\n    function curatorWithdrawalsLocked() external view returns (bool) {\n        return _reserveLossExitsLocked(_storage());\n    }\n\n    /// @notice Historical aggregate latch retained as a read-only compatibility surface.\n    function custodyLossUnabsorbed() external view returns (bool) {\n        ReserveStorage storage $ = _storage();\n        if ($.activeReserveLossArmId != 0 || $.activeReserveLossIncidentId != 0) return true;\n        if ($.reserveDeficit != 0 || $.recognizedSupplyReduction != 0 || $.totalPrincipalImpairment != 0) {\n            return true;\n        }\n        if (_liveShortfallUnits($) != 0) return true;\n        IMintRedeemController controller = $.lossController;\n        // Preserve W7's independently mutation-pinned fail-closed compatibility limb. The\n        // arm-bound custody workflow does not make a missing ADR-0034 absorber safe.\n        if (address(controller) == address(0) || address($.lossAbsorber) == address(0)) return true;\n        return controller.totalUSDfr() > controller.backingValue();\n    }\n\n    function _reserveLossExitsLocked(ReserveStorage storage $) private view returns (bool) {\n        if (\n            $.activeReserveLossArmId != 0 || $.activeReserveLossIncidentId != 0 || $.recognizedSupplyReduction != 0\n                || $.reserveDeficit != 0 || _liveShortfallUnits($) != 0\n        ) return true;\n        IMintRedeemController controller = $.lossController;\n        if (address(controller) == address(0) || address($.lossAbsorber) == address(0)) return true;\n        uint256 supply;\n        uint256 backing;\n        try controller.totalUSDfr() returns (uint256 supply_) {\n            supply = supply_;\n        } catch {\n            return true;\n        }\n        try controller.backingValue() returns (uint256 backing_) {\n            backing = backing_;\n        } catch {\n            return true;\n        }\n        return supply > backing;\n    }\n\n    /// @inheritdoc IReserveManager\n    function normalizeUSDC(uint256 amount) external pure returns (uint256) {\n        return ReserveStorageLib.normalize(amount);\n    }\n\n    /// @inheritdoc IReserveManager\n    function denormalizeUSDC(uint256 value) external pure returns (uint256) {\n        uint256 amount = ReserveStorageLib.denormalize(value);\n        if (ReserveStorageLib.normalize(amount) != value) revert ReserveManager_ValueNotUSDCExact(value);\n        return amount;\n    }\n\n    function _release(address to, uint256 amount) private {\n        if (to == address(0)) revert ReserveManager_ZeroAddress();\n        if (to == address(this)) revert ReserveManager_SelfDeployment();\n        if (amount == 0) revert ReserveManager_ZeroAmount();\n        ReserveStorage storage $ = _storage();\n        // R4-01: never pay an exit from a reserve whose recorded idle ledger is observably short.\n        ReserveStorageLib.requireIdleFullyCustodied($);\n        uint256 value = ReserveStorageLib.normalize(amount);\n        uint256 idleValue = ReserveStorageLib.normalize($.idleUSDCUnits);\n        if (value > idleValue) revert ReserveManager_InsufficientIdleValue(value, idleValue);\n        $.idleUSDCUnits -= amount;\n        $.usdcToken.safeTransfer(to, amount);\n        emit USDCReleased(to, amount);\n    }\n\n    function _requireReserveLossAdmin() private view {\n        if (!hasRole(Roles.RESERVE_ADMIN_ROLE, msg.sender)) {\n            revert ReserveManager_ReserveLossCallerNotAdmin(msg.sender);\n        }\n    }\n\n    function _requireActiveArm(ReserveStorage storage $, uint256 expectedArmId) private view returns (uint256 armId) {\n        armId = $.activeReserveLossArmId;\n        if (armId == 0) revert ReserveManager_NoActiveArm();\n        if (expectedArmId != armId) revert ReserveManager_ArmMismatch(armId, expectedArmId);\n    }\n\n    /// @dev A realized write-down consumes the corresponding conservative mark so the same loss\n    ///      is not counted once in face and again in the valuation adjustment.\n    function _backingValue(ReserveStorage storage $) private view returns (uint256) {\n        return ReserveAccrualViewsLib.backing($, false);\n    }\n\n    function _liveShortfallUnits(ReserveStorage storage $) private view returns (uint256) {\n        uint256 live = $.usdcToken.balanceOf(address(this));\n        return $.idleUSDCUnits > live ? $.idleUSDCUnits - live : 0;\n    }\n\n    /// @dev The caller needs only a validity bit. The earlier merge returned four additional\n    ///      values which no caller consumed, duplicating ABI decoders for every getter inside an\n    ///      EIP-170-constrained implementation. Keep the same six live checks through one strict\n    ///      word reader; compare CLOCK_MODE's complete canonical ABI encoding so a permissive\n    ///      fallback cannot satisfy the string call with a zero word.\n\n    function _requireNativeIdle() private view {\n        ReserveAccrualLib.requireIdle();\n        if (ReserveAccrualStorageLib.state().modules.token != address(0) && _reentrancyGuardEntered()) {\n            revert ReserveAccrualLib.ReserveAccrual_OperationInProgress();\n        }\n    }\n\n    /// @dev Return only a compiler-encoded typed view; no caller-controlled target or calldata.\n    function _returnEncodedView(bytes memory data) private pure {\n        assembly (\"memory-safe\") {\n            return(add(data, 32), mload(data))\n        }\n    }\n\n    function _grantRole(bytes32 role, address account) internal override returns (bool) {\n        _requireNativeIdle();\n        return super._grantRole(role, account);\n    }\n\n    function _revokeRole(bytes32 role, address account) internal override returns (bool) {\n        _requireNativeIdle();\n        return super._revokeRole(role, account);\n    }\n\n    function _authorizeUpgrade(address implementation) internal view override onlyRole(Roles.UPGRADER_ROLE) {\n        _requireNativeIdle();\n        ReserveAccrualLib.requireMixedImplementation(implementation);\n    }\n\n    /// @dev THE ONE NAMESPACED SLOT ASSIGNMENT, AND IT STAYS IN THIS FILE. `check-storage-layout`\n    ///      requires exactly one `$.slot` assignment in the file that declares the namespaced\n    ///      struct, which is how it binds a declaration to an ERC-7201 root. The libraries are\n    ///      handed the pointer rather than deriving it, so there is exactly one place in the\n    ///      repository that knows where this proxy's storage lives.\n    function _storage() private pure returns (ReserveStorage storage $) {\n        assembly {\n            $.slot := RESERVE_STORAGE_LOCATION\n        }\n    }\n}\n","deployed_bytecode":"0x60806040526004361061056a575f3560e01c80636af2fa06116102c5578063a895132011610176578063d0a6c794116100d4578063e84b51b91161008e578063e84b51b9146110ba578063ea613780146110d9578063eed8f72e146110ed578063f20b27591461110c578063f604c6df14611120578063f646f35f14611134578063fa7c427414611153575f5ffd5b8063d0a6c79414610ff0578063d141b0b014611004578063d547741f14611025578063d8b080c014611044578063d91e2d2614611063578063e2d252ad14611099575f5ffd5b8063b00424a611610130578063b00424a614610f41578063b1a8255a14610f60578063b54a151b14610d24578063b598401614610f7f578063bace10d114610f93578063c03ab92614610fb2578063ca258c9f14610fd1575f5ffd5b8063a895132014610e7f578063aae98a3814610e9e578063acbe8c3b14610ebd578063ad3cb1cc14610ed1578063ad95d8b614610f0e578063addabaea14610f22575f5ffd5b806389062cb91161022357806398ca56d8116101dd57806398ca56d814610db257806399f39ee114610dd15780639c13906d14610df05780639d2fae9b14610e0f5780639ead894414610e2e578063a217fddf14610e4d578063a5b6e52614610e60575f5ffd5b806389062cb914610d2457806391d1485414610d3857806394ac4bc114610d575780639655804e14610d6b57806397a298ad14610d7f57806397e1594e14610d93575f5ffd5b806376cfbb621161027f57806376cfbb6214610c3b57806376f830f014610c5a57806379a5027814610ca85780638456cb5914610cc95780638671a30114610cdd57806387f0f89a14610cfc5780638849837a14610d10575f5ffd5b80636af2fa0614610ba05780636c01c6da14610bb45780636fa4a33b14610bd357806370db380314610be7578063724f3d6914610bfb57806372790b3314610c1a575f5ffd5b806331e7a70f1161041f578063412838361161037d57806356b22bf21161033757806356b22bf214610add5780635c975abb14610afc57806363874b5814610b105780636616b01214610b2f5780636777079e14610b4357806367d2cd3d14610b6257806369249e5614610b81575f5ffd5b80634128383614610a5b578063431ecf5714610a6f5780634d7eb7a514610a835780634f1ef28614610a9757806352d1902d14610aaa5780635594d46f14610abe575f5ffd5b806336568abe116103d957806336568abe14610978578063366f124e1461099757806339d4bc94146109b65780633e413bee146109d55780633f29aa55146109f65780633f4ba83a14610a2857806340eadce814610a3c575f5ffd5b806331e7a70f146108a7578063334b7433146108c657806333810370146108e557806334ec2d411461090e5780633542b86a1461092d5780633575c7c41461094c575f5ffd5b806312851215116104cc578063248a9ca311610486578063248a9ca3146107a95780632a2061a7146107c85780632ab23cf3146107f75780632f2ff15d1461082b5780632fc3aadd1461084a5780633083b4e51461086957806331bb795c14610888575f5ffd5b806312851215146106fa5780631459457a1461070e578063167832561461072d5780631ca4ee241461074c5780631e5ca8891461076b578063215fc5691461078a575f5ffd5b806308d6b1241161052857806308d6b1241461062c5780630973f3151461064b5780630adc4b6c1461066a5780630c47d267146106895780630efec40c146106a85780630f6018c7146106c757806311af8243146106e6575f5ffd5b8062d91f4a1461056e57806301ffc9a71461058f57806302a24329146105c357806302df9274146105e25780630610ae1414610604578063065f2bfc14610618575b5f5ffd5b348015610579575f5ffd5b5061058d610588366004615257565b6111c0565b005b34801561059a575f5ffd5b506105ae6105a9366004615270565b61124a565b60405190151581526020015b60405180910390f35b3480156105ce575f5ffd5b5061058d6105dd366004615297565b611280565b3480156105ed575f5ffd5b506105f661130d565b6040519081526020016105ba565b34801561060f575f5ffd5b506105f661139a565b348015610623575f5ffd5b506105ae6113ac565b348015610637575f5ffd5b506105ae610646366004615322565b61151d565b348015610656575f5ffd5b5061058d610665366004615360565b6115a3565b348015610675575f5ffd5b5061058d6106843660046153cd565b611659565b348015610694575f5ffd5b506105f66106a33660046153ed565b6116ec565b3480156106b3575f5ffd5b506105f66106c23660046153ed565b611909565b3480156106d2575f5ffd5b506105f66106e13660046153ed565b6119a4565b3480156106f1575f5ffd5b506105f66119c0565b348015610705575f5ffd5b506105f66119d5565b348015610719575f5ffd5b5061058d610728366004615360565b611a1d565b348015610738575f5ffd5b5061058d610747366004615404565b611cda565b348015610757575f5ffd5b5061058d6107663660046153ed565b611d6d565b348015610776575f5ffd5b5061058d6107853660046153ed565b611d86565b348015610795575f5ffd5b506105ae6107a43660046153ed565b611e43565b3480156107b4575f5ffd5b506105f66107c33660046153ed565b611eb7565b3480156107d3575f5ffd5b506107dc611ed5565b604080519384526020840192909252908201526060016105ba565b348015610802575f5ffd5b506108166108113660046153ed565b611efd565b604080519283529015156020830152016105ba565b348015610836575f5ffd5b5061058d61084536600461541f565b611f9f565b348015610855575f5ffd5b5061058d6108643660046153cd565b611fc1565b348015610874575f5ffd5b5061058d610883366004615404565b61204c565b348015610893575f5ffd5b5061058d6108a23660046153ed565b6120d4565b3480156108b2575f5ffd5b506105f66108c136600461544d565b61212f565b3480156108d1575f5ffd5b5061058d6108e0366004615487565b6121d7565b3480156108f0575f5ffd5b506108f96122a1565b604080519283526020830191909152016105ba565b348015610919575f5ffd5b5061058d6109283660046154b8565b6122c1565b348015610938575f5ffd5b506105f66109473660046153ed565b61232a565b348015610957575f5ffd5b5061096b6109663660046153ed565b6123b9565b6040516105ba91906154d3565b348015610983575f5ffd5b5061058d61099236600461541f565b61247b565b3480156109a2575f5ffd5b5061058d6109b1366004615571565b6124ae565b3480156109c1575f5ffd5b5061058d6109d03660046153ed565b6124f8565b3480156109e0575f5ffd5b506109e9612580565b6040516105ba91906155b3565b348015610a01575f5ffd5b507f17085a5db666070eb4aa0aac3c233b268ac6d0b0c76e1646dbb52fd255f00c056105f6565b348015610a33575f5ffd5b5061058d612598565b348015610a47575f5ffd5b506105f6610a563660046153ed565b6125bf565b348015610a66575f5ffd5b5061058d6125f9565b348015610a7a575f5ffd5b506107dc61264d565b348015610a8e575f5ffd5b506109e96126f3565b61058d610aa5366004615631565b61270e565b348015610ab5575f5ffd5b506105f6612729565b348015610ac9575f5ffd5b506105f6610ad83660046153ed565b612745565b348015610ae8575f5ffd5b506105f6610af73660046156bd565b61277f565b348015610b07575f5ffd5b506105ae612a1c565b348015610b1b575f5ffd5b5061058d610b2a3660046156e7565b612a30565b348015610b3a575f5ffd5b506109e9612c1c565b348015610b4e575f5ffd5b506108f9610b5d36600461571e565b612c37565b348015610b6d575f5ffd5b506105f6610b7c36600461544d565b612cc9565b348015610b8c575f5ffd5b5061058d610b9b3660046153cd565b612d9a565b348015610bab575f5ffd5b506105f6612e56565b348015610bbf575f5ffd5b5061058d610bce366004615739565b612e68565b348015610bde575f5ffd5b506105f6612eb2565b348015610bf2575f5ffd5b5061058d612f06565b348015610c06575f5ffd5b506105f6610c153660046153cd565b612f72565b348015610c25575f5ffd5b50610c2e613023565b6040516105ba9190615760565b348015610c46575f5ffd5b5061058d610c553660046153cd565b6130a4565b348015610c65575f5ffd5b50610c6e6130d8565b604080516001600160a01b03968716815294861660208601529285169284019290925283166060830152909116608082015260a0016105ba565b348015610cb3575f5ffd5b50610cbc613124565b6040516105ba91906157ca565b348015610cd4575f5ffd5b5061058d6131c9565b348015610ce8575f5ffd5b506105f6610cf73660046153ed565b6131f0565b348015610d07575f5ffd5b506105f6613228565b348015610d1b575f5ffd5b506105f6613323565b348015610d2f575f5ffd5b506105ae613346565b348015610d43575f5ffd5b506105ae610d5236600461541f565b613357565b348015610d62575f5ffd5b506105f661338b565b348015610d76575f5ffd5b5061058d61339d565b348015610d8a575f5ffd5b506109e96133ef565b348015610d9e575f5ffd5b5061058d610dad3660046156e7565b61345b565b348015610dbd575f5ffd5b5061058d610dcc366004615404565b613588565b348015610ddc575f5ffd5b5061058d610deb3660046153ed565b6135bc565b348015610dfb575f5ffd5b506105f6610e0a3660046153ed565b6135e6565b348015610e1a575f5ffd5b506105f6610e293660046153cd565b613602565b348015610e39575f5ffd5b506108f9610e483660046156e7565b6136f5565b348015610e58575f5ffd5b506105f65f81565b348015610e6b575f5ffd5b5061058d610e7a3660046153ed565b613ab6565b348015610e8a575f5ffd5b5061058d610e993660046153cd565b613ae0565b348015610ea9575f5ffd5b5061058d610eb83660046153ed565b613b6a565b348015610ec8575f5ffd5b506105f6613b9e565b348015610edc575f5ffd5b50610f01604051806040016040528060058152602001640352e302e360dc1b81525081565b6040516105ba9190615836565b348015610f19575f5ffd5b506105f6613bb0565b348015610f2d575f5ffd5b506105f6610f3c36600461586b565b613c56565b348015610f4c575f5ffd5b506105ae610f5b3660046153ed565b613cd3565b348015610f6b575f5ffd5b5061058d610f7a366004615898565b613cf2565b348015610f8a575f5ffd5b506105f6613d59565b348015610f9e575f5ffd5b506108f9610fad3660046153ed565b613d6b565b348015610fbd575f5ffd5b506105f6610fcc3660046153ed565b613e1d565b348015610fdc575f5ffd5b5061058d610feb3660046156bd565b613e27565b348015610ffb575f5ffd5b506105f6613e7b565b34801561100f575f5ffd5b50611018613ec9565b6040516105ba91906158c2565b348015611030575f5ffd5b5061058d61103f36600461541f565b613f6f565b34801561104f575f5ffd5b506105f661105e3660046153cd565b613f8b565b34801561106e575f5ffd5b50611077614036565b60408051948552602085019390935291830152151560608201526080016105ba565b3480156110a4575f5ffd5b506110ad614083565b6040516105ba9190615946565b3480156110c5575f5ffd5b5061058d6110d4366004615a44565b6140d4565b3480156110e4575f5ffd5b5061058d61411c565b3480156110f8575f5ffd5b506105f66111073660046153ed565b614126565b348015611117575f5ffd5b506105ae614151565b34801561112b575f5ffd5b5061058d614166565b34801561113f575f5ffd5b5061058d61114e3660046153cd565b6141ce565b34801561115e575f5ffd5b5061117261116d3660046153ed565b614202565b6040516105ba91905f60a08201905082518252602083015160208301526001600160401b03604084015116604083015260608301511515606083015260808301511515608083015292915050565b5f6111ca81614264565b6111d261426e565b738768f6f689d9ba1f0c08d418af8ff31ac820a4a563715870ff6111f46142a3565b846040518363ffffffff1660e01b8152600401611212929190615a67565b5f6040518083038186803b158015611228575f5ffd5b505af415801561123a573d5f5f3e3d5ffd5b505050506112466142c7565b5050565b5f6001600160e01b03198216637965db0b60e01b148061127a57506301ffc9a760e01b6001600160e01b03198316145b92915050565b5f61128a81614264565b61129261426e565b7355cd23031ce9268a19552341d4041530868ae624639e1d1d216112b46142a3565b85856040518463ffffffff1660e01b81526004016112d493929190615b36565b5f6040518083038186803b1580156112ea575f5ffd5b505af41580156112fc573d5f5f3e3d5ffd5b505050506113086142c7565b505050565b5f73d999970138c2397ca8582710676a29da5b6da23d6385ef8b796113306142a3565b6040516001600160e01b031960e084901b16815260048101919091525f60248201526044015b602060405180830381865af4158015611371573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113959190615b6b565b905090565b5f6113a36142d7565b60370154905090565b5f5f6113b66142a3565b905080601801545f1415806113ce5750600681015415155b156113db57600191505090565b60088101541515806113f05750601281015415155b806113fe5750601b81015415155b1561140b57600191505090565b611414816142fb565b1561142157600191505090565b60058101546001600160a01b0316801580611447575060048201546001600160a01b0316155b156114555760019250505090565b806001600160a01b0316630e9141926040518163ffffffff1660e01b8152600401602060405180830381865afa158015611491573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114b59190615b6b565b816001600160a01b0316632f6b1f626040518163ffffffff1660e01b8152600401602060405180830381865afa1580156114f1573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115159190615b6b565b119250505090565b6040516302167b9760e41b81525f9073353aea61b5760644560f98c07c56752478ec591d90632167b9709061155a90879087908790600401615b82565b602060405180830381865af4158015611575573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115999190615ba6565b90505b9392505050565b6115ab614390565b5f6115b581614264565b73e0b4679481e5c355e8fb783aa6c73159bcf6b1396316b5eeb76115d76142a3565b6040516001600160e01b031960e084901b16815260048101919091526001600160a01b03808a166024830152808916604483015280881660648301528087166084830152851660a482015260c4015f6040518083038186803b15801561163b575f5ffd5b505af415801561164d573d5f5f3e3d5ffd5b50505050505050505050565b611661614390565b5f61166b81614264565b7369e62255248a7240fc5189671d20edd1a069e105638e348b3c61168d6142a3565b6040516001600160e01b031960e084901b168152600481019190915260248101869052604481018590526064015b5f6040518083038186803b1580156116d1575f5ffd5b505af41580156116e3573d5f5f3e3d5ffd5b50505050505050565b5f6116f5614390565b6116fd61426e565b815f0361171d5760405163bc25207f60e01b815260040160405180910390fd5b5f6117266142a3565b80546040516370a0823160e01b81529192505f916001600160a01b03909116906370a082319061175a9030906004016155b3565b602060405180830381865afa158015611775573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117999190615b6b565b82549091506117b3906001600160a01b03163330876143dd565b81546040516370a0823160e01b81525f9183916001600160a01b03909116906370a08231906117e69030906004016155b3565b602060405180830381865afa158015611801573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906118259190615b6b565b61182f9190615bd5565b9050805f0361185157604051630255c60b60e11b815260040160405180910390fd5b84811461188057604051634953408b60e01b815260048101869052602481018290526044015b60405180910390fd5b80836001015f8282546118939190615be8565b909155506118a2905081614437565b9350337fdfe70afea21e3db591383c6e83d6952e0120f6f10e7dd6be79b3fbd2647590fa82866118d187614447565b600888015460408051948552602085019390935291830152606082015260800160405180910390a25050506119046142c7565b919050565b5f61191261426e565b73662396fdb7220639d61f0491284b5277062c3eeb63f7aa64156119346142a3565b846040518363ffffffff1660e01b815260040161195b929190918252602082015260400190565b602060405180830381865af4158015611976573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061199a9190615b6b565b90506119046142c7565b5f6119ad6142a3565b5f928352601a0160205250604090205490565b5f6113956119cc6142a3565b60010154614437565b5f738aeb59d677899431d029dbc6c8dfc8fad2aeb82163c92c9bdb6040518163ffffffff1660e01b8152600401602060405180830381865af4158015611371573d5f5f3e3d5ffd5b5f611a26614488565b805490915060ff600160401b82041615906001600160401b03165f81158015611a4c5750825b90505f826001600160401b03166001148015611a675750303b155b905081158015611a75575080155b15611a935760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff191660011785558315611abd57845460ff60401b1916600160401b1785555b6001600160a01b038a161580611ada57506001600160a01b038916155b80611aec57506001600160a01b038816155b80611afe57506001600160a01b038716155b80611b1057506001600160a01b038616155b15611b2e57604051636cd2038560e11b815260040160405180910390fd5b5f866001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b6b573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611b8f9190615bfb565b90508060ff16600614611bba57604051632902554b60e21b815260ff82166004820152602401611877565b611bc26144b0565b611bca6144b0565b611bd26144b8565b611bda6144b0565b611be45f8c6144c8565b50611c0f7fcb6c915afba301a06d8c17327f1f6eec8e262e5feb9a4db38c9ac4d14eb366a38b6144c8565b50611c275f516020615f115f395f51905f528a6144c8565b50611c527f189ab7a9244df0848122154315af71fe140f3db0fe014031783b0946b8c9d2e3896144c8565b505f611c5c6142a3565b80546001600160a01b038a166001600160a01b0319909116178155601601805461ff0019166101001790555050831561164d57845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a150505050505050505050565b611ce2614390565b5f611cec81614264565b73e0b4679481e5c355e8fb783aa6c73159bcf6b13963d015a196611d0e6142a3565b6040516001600160e01b031960e084901b16815260048101919091526001600160a01b03851660248201526044015b5f6040518083038186803b158015611d53575f5ffd5b505af4158015611d65573d5f5f3e3d5ffd5b505050505050565b60405163b7b6414d60e01b815260040160405180910390fd5b611d8e614390565b5f611d976142a3565b60048101549091506001600160a01b03163314611dc957336040516309660a1360e11b815260040161187791906155b3565b815f03611de95760405163bc25207f60e01b815260040160405180910390fd5b5f8282601d0154611dfa9190615be8565b601d830181905560408051858152602081018390529192507fb92037a3944a13f75b8b303a4c2d15d6deac77392612e3ddc826aa1dc6b5092591015b60405180910390a1505050565b6040516342b84e3160e11b8152600481018290525f9073662396fdb7220639d61f0491284b5277062c3eeb906385709c6290602401602060405180830381865af4158015611e93573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061127a9190615ba6565b5f5f611ec16144db565b5f9384526020525050604090206001015490565b5f5f5f5f611ee16142a3565b6010810154601182015460129092015490969195509350915050565b5f5f611f0761426e565b738aeb59d677899431d029dbc6c8dfc8fad2aeb821637bc951eb611f296142a3565b856040518363ffffffff1660e01b8152600401611f50929190918252602082015260400190565b6040805180830381865af4158015611f6a573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f8e9190615c16565b91509150611f9a6142c7565b915091565b611fa882611eb7565b611fb181614264565b611fbb83836144c8565b50505050565b611fc9614390565b5f516020615ef15f395f51905f52611fe081614264565b611fe86144ff565b611ff183614525565b736cb6ff7bed904cfdf8da7dc30fd8446ad89d4e056341c81f076120136142a3565b6040516001600160e01b031960e084901b16815260048101919091526024810186905260448101859052600160648201526084016116bb565b612054614390565b5f61205e81614264565b6040516381bac14f60e01b81527311905fea06726c3cd1d43befd994d11fcce0d79f906381bac14f906120959085906004016155b3565b602060405180830381865af41580156120b0573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113089190615c3a565b6120dc614390565b5f6120e681614264565b7369e62255248a7240fc5189671d20edd1a069e10563f5ed77e76121086142a3565b846040518363ffffffff1660e01b8152600401611d3d929190918252602082015260400190565b5f61213861426e565b6121406144ff565b73d72860da3bbbc064ba19ac5c8a9e49022b58cdb763344627156121626142a3565b878787876040518663ffffffff1660e01b8152600401612186959493929190615c55565b602060405180830381865af41580156121a1573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906121c59190615b6b565b90506121cf6142c7565b949350505050565b6121df614390565b5f516020615ef15f395f51905f526121f681614264565b6121fe61426e565b6122066144ff565b61220f84614525565b736cb6ff7bed904cfdf8da7dc30fd8446ad89d4e05630f1d41076122316142a3565b6040516001600160e01b031960e084901b1681526004810191909152602481018790526001600160a01b0386166044820152606481018590526084015f6040518083038186803b158015612283575f5ffd5b505af4158015612295573d5f5f3e3d5ffd5b50505050611fbb6142c7565b5f5f5f6122ac6142a3565b90508060060154816007015492509250509091565b6122c9614390565b5f6122d381614264565b5f6122dc6142a3565b6016810180548515156101000261ff00199091161790556040519091507f3e1d16535c5af6624bc3d6b81a0d9c551d9b46bd3c8f17301dda39f69fb22a2990611e3690851515815260200190565b5f73d999970138c2397ca8582710676a29da5b6da23d6356a75db461234d6142a3565b6040516001600160e01b031960e084901b1681526004810191909152602481018590525f60448201526064015b602060405180830381865af4158015612395573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061127a9190615b6b565b60408051610120810182525f80825260208201819052818301819052606082018190526080820181905260a0820181905260c0820181905260e0820181905261010082015290516303c0053960e31b8152600481018390526119049073d999970138c2397ca8582710676a29da5b6da23d90631e0029c8906024015b5f60405180830381865af415801561244f573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526124769190810190615c81565b61458f565b6001600160a01b03811633146124a45760405163334bd91960e11b815260040160405180910390fd5b6113088282614597565b6124b661426e565b73d72860da3bbbc064ba19ac5c8a9e49022b58cdb763c8a47fcf6124d86142a3565b84846040518463ffffffff1660e01b815260040161121293929190615d1e565b61250061426e565b738aeb59d677899431d029dbc6c8dfc8fad2aeb821635d08936b6125226142a3565b836040518363ffffffff1660e01b8152600401612549929190918252602082015260400190565b5f6040518083038186803b15801561255f575f5ffd5b505af4158015612571573d5f5f3e3d5ffd5b5050505061257d6142c7565b50565b5f6125896142a3565b546001600160a01b0316919050565b6125a0614390565b5f516020615f115f395f51905f526125b781614264565b61257d6145aa565b604051632e3959db60e11b8152600481018290525f9073d999970138c2397ca8582710676a29da5b6da23d90635c72b3b69060240161237a565b738768f6f689d9ba1f0c08d418af8ff31ac820a4a5633dae371f6040518163ffffffff1660e01b81526004015f6040518083038186803b15801561263b575f5ffd5b505af4158015611fbb573d5f5f3e3d5ffd5b5f5f5f5f6126596142a3565b600181015481546040516370a0823160e01b81529196509192506001600160a01b03909116906370a08231906126939030906004016155b3565b602060405180830381865afa1580156126ae573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906126d29190615b6b565b92508284116126e1575f6126eb565b6126eb8385615bd5565b915050909192565b5f6126fc6142a3565b600501546001600160a01b0316919050565b612716614600565b61271f8261468e565b61124682826146f7565b5f6127326147aa565b505f516020615ed15f395f51905f525b90565b604051630bd30f1160e01b8152600481018290525f90738aeb59d677899431d029dbc6c8dfc8fad2aeb82190630bd30f119060240161237a565b5f612788614390565b61279061426e565b6127986144ff565b6127c27f7b765e0e932d348852a6f810bfa1ab891e259123f02db8cdcde614c57022335733613357565b1580156127e357506127e15f516020615ef15f395f51905f5233613357565b155b156128035733604051631d4a04d360e21b815260040161187791906155b3565b6001600160a01b03831661282a57604051636cd2038560e11b815260040160405180910390fd5b815f0361284a5760405163bc25207f60e01b815260040160405180910390fd5b5f6128536142a3565b80546040516370a0823160e01b81529192505f916001600160a01b03909116906370a08231906128879030906004016155b3565b602060405180830381865afa1580156128a2573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128c69190615b6b565b82549091506128e0906001600160a01b03168630876143dd565b81546040516370a0823160e01b81525f9183916001600160a01b03909116906370a08231906129139030906004016155b3565b602060405180830381865afa15801561292e573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129529190615b6b565b61295c9190615bd5565b9050805f0361297e57604051630255c60b60e11b815260040160405180910390fd5b8481146129a857604051634953408b60e01b81526004810186905260248101829052604401611877565b80836001015f8282546129bb9190615be8565b909155506129ca905081614437565b60408051878152602081018390529195506001600160a01b038816917fdf761661d51ab4147355430c8891e0dc7406b6aece4d2b564ccd87e0baa6dfd9910160405180910390a250505061127a6142c7565b5f5f612a266147f3565b5460ff1692915050565b612a38614390565b5f612a4281614264565b825f03612a625760405163bc25207f60e01b815260040160405180910390fd5b81612a805760405163557b260d60e11b815260040160405180910390fd5b5f612a896142a3565b9050612a936142d7565b6031015460ff1615612b1a576040516318b46b2160e31b81526004810182905260248101869052738aeb59d677899431d029dbc6c8dfc8fad2aeb8219063c5a3590890604401602060405180830381865af4158015612af4573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612b189190615b6b565b505b5f858152601c820160209081526040808320546003850190925290912054612b428282615bd5565b861115612b7f578686612b558484615bd5565b60405163770505cd60e01b8152600481019390935260248301919091526044820152606401611877565b5f612b8a8784615be8565b5f898152601c860160205260408120829055601b86015491925090612bb0908990615be8565b601b86018190559050887fb0974ca28c96a4d84cc3a64f95269c76ed8bf8728dac225d424fe4e29d5c38f5898484612be78a614447565b604080519485526020850193909352918301526060820152608081018a905260a00160405180910390a2505050505050505050565b5f612c256142a3565b600401546001600160a01b0316919050565b5f5f612c4161426e565b738768f6f689d9ba1f0c08d418af8ff31ac820a4a5633f9d84ed612c636142a3565b6040516001600160e01b031960e084901b168152600481019190915260ff861660248201526044016040805180830381865af4158015612ca5573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f8e9190615dab565b5f612cd2614390565b5f516020615ef15f395f51905f52612ce981614264565b612cf161426e565b612cf96144ff565b612d0286614817565b736cb6ff7bed904cfdf8da7dc30fd8446ad89d4e0563d7f91645612d246142a3565b888888886040518663ffffffff1660e01b8152600401612d48959493929190615c55565b602060405180830381865af4158015612d63573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612d879190615b6b565b9150612d916142c7565b50949350505050565b612da2614390565b5f516020615ef15f395f51905f52612db981614264565b612dc16142d7565b6031015460ff1615612e3457604051635bd45aa160e01b8152600481018490526024810183905273d72860da3bbbc064ba19ac5c8a9e49022b58cdb790635bd45aa1906044015f6040518083038186803b158015612e1d575f5ffd5b505af4158015612e2f573d5f5f3e3d5ffd5b505050505b736cb6ff7bed904cfdf8da7dc30fd8446ad89d4e0563b430b40261168d6142a3565b5f612e5f6142a3565b60010154905090565b612e7061426e565b73d72860da3bbbc064ba19ac5c8a9e49022b58cdb763d243be1a612e926142a3565b84846040518463ffffffff1660e01b815260040161121293929190615dcd565b5f73d999970138c2397ca8582710676a29da5b6da23d6356a75db4612ed56142a3565b6040516001600160e01b031960e084901b16815260048101919091525f602482015260016044820152606401611356565b612f0e614390565b5f612f176142d7565b603181015490915060ff1680612f3857506038810154600160901b900460ff165b80612f465750603281015415155b80612f545750603781015415155b1561257d57604051632e8a9a8760e11b815260040160405180910390fd5b5f612f7b614390565b612f8361426e565b612f8b614847565b7369e62255248a7240fc5189671d20edd1a069e105636d6259d4612fad6142a3565b6040516001600160e01b031960e084901b16815260048101919091526024810186905260448101859052606401602060405180830381865af4158015612ff5573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130199190615b6b565b905061127a6142c7565b6040805160e0810182525f80825260208201819052918101829052606081018290526080810182905260a0810182905260c0810191909152612742738768f6f689d9ba1f0c08d418af8ff31ac820a4a563ab87e6096040518163ffffffff1660e01b81526004015f60405180830381865af415801561244f573d5f5f3e3d5ffd5b6130ac614390565b5f6130b681614264565b7369e62255248a7240fc5189671d20edd1a069e1056329b8cfc761168d6142a3565b5f5f5f5f5f5f6130e66142a3565b600a810154600b820154600c830154600e840154600f909401546001600160a01b039384169b9284169a509083169850928216965091169350915050565b6131806040518061012001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f6001600160a01b031681526020015f6001600160401b031681526020015f151581526020015f151581525090565b612742738768f6f689d9ba1f0c08d418af8ff31ac820a4a5636666d3726040518163ffffffff1660e01b81526004015f60405180830381865af415801561244f573d5f5f3e3d5ffd5b6131d1614390565b5f516020615f115f395f51905f526131e881614264565b61257d614890565b5f5f6131fb836148d6565b90508261320782614437565b1461127a57604051630684073360e21b815260048101849052602401611877565b5f613231614390565b61323961426e565b5f6132426142a3565b80546040516370a0823160e01b81529192505f916001600160a01b03909116906370a08231906132769030906004016155b3565b602060405180830381865afa158015613291573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906132b59190615b6b565b60018301549091508181116132ca575f6132d4565b6132d48282615bd5565b60408051838152602081018590529081018290529094507f4b9a8f42a44d48811eb4258375f7eb86085ce952140b71df79c426efc09733b39060600160405180910390a15050506127426142c7565b5f5f6133356133306142a3565b6142fb565b905061334081614437565b91505090565b5f6113956133526142a3565b6148e6565b5f5f6133616144db565b5f948552602090815260408086206001600160a01b03959095168652939052505090205460ff1690565b5f6133946142a3565b601d0154905090565b5f6133a781614264565b6133af61426e565b738768f6f689d9ba1f0c08d418af8ff31ac820a4a563869467c96133d16142a3565b6040518263ffffffff1660e01b815260040161254991815260200190565b5f7311905fea06726c3cd1d43befd994d11fcce0d79f637b1039996040518163ffffffff1660e01b8152600401602060405180830381865af4158015613437573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113959190615c3a565b613463614390565b5f61346d81614264565b825f0361348d5760405163bc25207f60e01b815260040160405180910390fd5b816134ab5760405163557b260d60e11b815260040160405180910390fd5b5f6134b46142a3565b5f868152601c82016020526040902054909150808511156134f95760405163d1eaa8e160e01b8152600481018790526024810186905260448101829052606401611877565b5f6135048683615bd5565b5f888152601c850160205260408120829055601b8501549192509061352a908890615bd5565b601b850181905560408051898152602081018590529081018290526060810188905290915088907f3ab57d7bbb971777f2c003e6062120261bd37627de94c0cf82109c6593c478849060800160405180910390a25050505050505050565b613590614390565b5f61359a81614264565b73e0b4679481e5c355e8fb783aa6c73159bcf6b1396307373853611d0e6142a3565b6135c461426e565b73d72860da3bbbc064ba19ac5c8a9e49022b58cdb7634d23e1dc6125226142a3565b5f6135ef6142a3565b5f928352601c0160205250604090205490565b5f61360b614390565b5f6136146142a3565b60048101549091506001600160a01b0316331461364657336040516309660a1360e11b815260040161187791906155b3565b601d8101545f81900361365d575f9250505061127a565b5f858152601c83016020526040902054848111156136785750835b8082106136855780613687565b815b9350835f0361369b575f935050505061127a565b5f6136a68584615bd5565b601d8501819055604080518781526020810183905291925088917f59579095e479f9ef696f9072e4c489cde86b02eda5cd00218e3862081081a1dd910160405180910390a25050505092915050565b5f5f6136ff614390565b61370761426e565b61370f614847565b5f6137186142a3565b90505f6137258288614a4c565b6019830154909150868114613757576040516355046ad760e11b81526004810182905260248101889052604401611877565b5f613761846142fb565b9050805f0361378257604051626b8a0360e31b815260040160405180910390fd5b61378b81614437565b9450868511156137b85760405163083e7d8160e11b81526004810186905260248101889052604401611877565b6137c183614a9c565b95506137d186600160ff1b111590565b6137dd576137dd615e70565b60068401545f819003613882575f87815260098601602052604090205460ff161561381e57604051631902098360e21b815260048101889052602401611877565b5f87815260098601602052604090819020805460ff191660011790556006860188905551849088907fc14b7ab566185952b484a6411b322acff0571957630185c0a7008dcfee38b99b90613875908d815260200190565b60405180910390a36138ac565b8681146138ac576040516308208cab60e21b81526004810182905260248101889052604401611877565b600785018990555f848152601a86016020526040812080548492906138d2908490615be8565b9091555050604051634c1c05b760e11b815260048101869052738768f6f689d9ba1f0c08d418af8ff31ac820a4a5906398380b6e906024015f6040518083038186803b158015613920575f5ffd5b505af4158015613932573d5f5f3e3d5ffd5b505060405163ba19528f60e01b815260048101889052602481018590526044810189905273a7ea67345ea180ed41093cc6b9660af8a3744913925063ba19528f91506064015f6040518083038186803b15801561398d575f5ffd5b505af415801561399f573d5f5f3e3d5ffd5b5050505084601201545f14613a155760405163034cd85160e11b8152600481018690526024810188905273a7ea67345ea180ed41093cc6b9660af8a374491390630699b0a2906044015f6040518083038186803b1580156139fe575f5ffd5b505af4158015613a10573d5f5f3e3d5ffd5b505050505b7fb5a35ece8924c9d143ef885d113989a1896eb4898e6fe7f72eb5e5648911e55686613a448760010154614437565b6040805192835260208301919091520160405180910390a160408051898152602081018890529081018a9052879085907f9a634e851f7a67ae03554fc3908ef8330b3742193155bc9c3d70728ac7c6e9ac9060600160405180910390a35050505050613aae6142c7565b935093915050565b613abe61426e565b73d72860da3bbbc064ba19ac5c8a9e49022b58cdb76323e0b66a6125226142a3565b613ae8614390565b5f516020615ef15f395f51905f52613aff81614264565b613b076144ff565b613b1083614817565b736cb6ff7bed904cfdf8da7dc30fd8446ad89d4e056341c81f07613b326142a3565b6040516001600160e01b031960e084901b168152600481019190915260248101869052604481018590525f60648201526084016116bb565b613b72614390565b5f613b7c81614264565b7369e62255248a7240fc5189671d20edd1a069e1056325269b836121086142a3565b5f613ba76142a3565b60080154905090565b5f5f613bba6142a3565b80546040516370a0823160e01b81529192505f916001600160a01b03909116906370a0823190613bee9030906004016155b3565b602060405180830381865afa158015613c09573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613c2d9190615b6b565b905081600101548111613c40575f613c4f565b6001820154613c4f9082615bd5565b9250505090565b604051633879345760e01b815260ff83166004820152602481018290525f90738aeb59d677899431d029dbc6c8dfc8fad2aeb82190633879345790604401602060405180830381865af4158015613caf573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061159c9190615b6b565b5f613cdc6142a3565b5f92835260090160205250604090205460ff1690565b613cfa61426e565b738768f6f689d9ba1f0c08d418af8ff31ac820a4a563c26c07cd613d1c6142a3565b6040516001600160e01b031960e084901b168152600481019190915261ffff851660248201526001600160a01b0384166044820152606401611212565b5f613d626142a3565b601b0154905090565b5f5f613d75614390565b5f516020615f115f395f51905f52613d8c81614264565b7369e62255248a7240fc5189671d20edd1a069e1056385f92f7f613dae6142a3565b866040518363ffffffff1660e01b8152600401613dd5929190918252602082015260400190565b6040805180830381865af4158015613def573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613e139190615dab565b9250925050915091565b5f61127a82614437565b613e2f614390565b7f7b765e0e932d348852a6f810bfa1ab891e259123f02db8cdcde614c570223357613e5981614264565b613e6161426e565b613e696144ff565b613e738383614af0565b6113086142c7565b5f73d999970138c2397ca8582710676a29da5b6da23d6385ef8b79613e9e6142a3565b6040516001600160e01b031960e084901b168152600481019190915260016024820152604401611356565b613f266040518061012001604052805f81526020015f81526020015f6001600160401b031681526020015f63ffffffff1681526020015f63ffffffff1681526020015f81526020015f81526020015f81526020015f151581525090565b61274273179e54e2096c93bb1c835a9797a5b70946086de963b0ffbb806040518163ffffffff1660e01b81526004015f60405180830381865af415801561244f573d5f5f3e3d5ffd5b613f7882611eb7565b613f8181614264565b611fbb8383614597565b5f613f94614390565b5f613f9e81614264565b7369e62255248a7240fc5189671d20edd1a069e10563976234cc613fc06142a3565b6040516001600160e01b031960e084901b16815260048101919091526024810187905260448101869052606401602060405180830381865af4158015614008573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061402c9190615b6b565b91505b5092915050565b5f5f5f5f5f6140436142a3565b60188101549550905084156140605761405b85614a9c565b614062565b5f5b60198201546016909201549596909591945061010090910460ff1692509050565b61408b6151c3565b612742738768f6f689d9ba1f0c08d418af8ff31ac820a4a563a3f8a30a6040518163ffffffff1660e01b81526004015f60405180830381865af415801561244f573d5f5f3e3d5ffd5b6140dc61426e565b6040516334e01c8f60e11b815260048101839052811515602482015273d72860da3bbbc064ba19ac5c8a9e49022b58cdb7906369c0391e90604401611212565b614124614c33565b565b5f61412f61426e565b738aeb59d677899431d029dbc6c8dfc8fad2aeb82163c5a359086119346142a3565b5f61415a6142d7565b603f015460ff16919050565b61416e61426e565b738768f6f689d9ba1f0c08d418af8ff31ac820a4a563f604c6df6040518163ffffffff1660e01b81526004015f6040518083038186803b1580156141b0575f5ffd5b505af41580156141c2573d5f5f3e3d5ffd5b505050506141246142c7565b6141d6614390565b5f6141e081614264565b7369e62255248a7240fc5189671d20edd1a069e1056387386d3c61168d6142a3565b6040805160a0810182525f80825260208201819052818301819052606082018190526080820152905163266e2b0360e11b8152600481018390526119049073d999970138c2397ca8582710676a29da5b6da23d90634cdc560690602401612435565b61257d8133614c96565b5f614277614ccf565b80549091506001190161429d57604051633ee5aeb560e01b815260040160405180910390fd5b60029055565b7fc49ad79e2b58679c441432bede06c67f7802343349e70ccf00d8d1ce92bb1b0090565b5f6142d0614ccf565b6001905550565b7f2420c1d967401a6739c551e175fd4dfa8e9cd5ee804155e89721bed004930b0090565b80546040516370a0823160e01b81525f9182916001600160a01b03909116906370a082319061432e9030906004016155b3565b602060405180830381865afa158015614349573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061436d9190615b6b565b905080836001015411614380575f61159c565b80836001015461159c9190615bd5565b614398614c33565b5f6143a16142d7565b601101546001600160a01b0316148015906143bf57506143bf614cf3565b1561412457604051639de6bad160e01b815260040160405180910390fd5b611fbb84856001600160a01b03166323b872dd86868660405160240161440593929190615b82565b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050614d07565b5f61127a64e8d4a5100083615e84565b6040516385ef8b7960e01b8152600481018290525f602482018190529073d999970138c2397ca8582710676a29da5b6da23d906385ef8b799060440161237a565b5f807ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0061127a565b614124614d6a565b6144c0614d6a565b614124614d8f565b5f6144d1614390565b61159c8383614d97565b7f02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b62680090565b614507612a1c565b156141245760405163d93c066560e01b815260040160405180910390fd5b5f61452e6142d7565b603181015490915060ff16614541575050565b6014810154614558906001600160a01b0316614e35565b5f82815260188201602052604090206005015460ff1615611246576040516328f7b79760e11b815260048101839052602401611877565b805160208201f35b5f6145a0614390565b61159c8383614e6f565b6145b2614ee5565b5f6145bb6147f3565b805460ff1916815590507f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516145f591906155b3565b60405180910390a150565b306001600160a01b037f00000000000000000000000099b4dfa4e1344273d5335bd90de1dea3a02b9c3a16148061467057507f00000000000000000000000099b4dfa4e1344273d5335bd90de1dea3a02b9c3a6001600160a01b0316614664614f0a565b6001600160a01b031614155b156141245760405163703e46dd60e11b815260040160405180910390fd5b7f189ab7a9244df0848122154315af71fe140f3db0fe014031783b0946b8c9d2e36146b881614264565b6146c0614390565b604051633e619e5f60e11b8152738768f6f689d9ba1f0c08d418af8ff31ac820a4a590637cc33cbe90611d3d9085906004016155b3565b816001600160a01b03166352d1902d6040518163ffffffff1660e01b8152600401602060405180830381865afa925050508015614751575060408051601f3d908101601f1916820190925261474e91810190615b6b565b60015b6147705781604051634c9c8ce360e01b815260040161187791906155b3565b5f516020615ed15f395f51905f5281146147a057604051632a87526960e21b815260048101829052602401611877565b6113088383614f1e565b306001600160a01b037f00000000000000000000000099b4dfa4e1344273d5335bd90de1dea3a02b9c3a16146141245760405163703e46dd60e11b815260040160405180910390fd5b7fcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f0330090565b61481f6142d7565b6031015460ff161561257d576040516328f7b79760e11b815260048101829052602401611877565b6148717fcb6c915afba301a06d8c17327f1f6eec8e262e5feb9a4db38c9ac4d14eb366a333613357565b61412457336040516350c7779760e11b815260040161187791906155b3565b6148986144ff565b5f6148a16147f3565b805460ff1916600117815590507f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586145e83390565b5f61127a64e8d4a5100083615e9b565b5f81601801545f1415806148fd5750600682015415155b8061490b5750601282015415155b806149195750600882015415155b8061492b5750614928826142fb565b15155b1561493857506001919050565b60058201546001600160a01b031680158061495e575060048301546001600160a01b0316155b1561496c5750600192915050565b5f5f826001600160a01b0316632f6b1f626040518163ffffffff1660e01b8152600401602060405180830381865afa9250505080156149c8575060408051601f3d908101601f191682019092526149c591810190615b6b565b60015b6149d757506001949350505050565b9150826001600160a01b0316630e9141926040518163ffffffff1660e01b8152600401602060405180830381865afa925050508015614a33575060408051601f3d908101601f19168201909252614a3091810190615b6b565b60015b614a4257506001949350505050565b9050109392505050565b60188201545f819003614a72576040516342e5afaf60e11b815260040160405180910390fd5b80821461127a57604051635c252f3b60e11b81526004810182905260248101839052604401611877565b5f811580614aae5750600160ff1b8210155b15614acf57604051635fea8ef360e01b815260048101839052602401611877565b614ada825f19615bd5565b9050600160ff1b81101561190457611904615e70565b6001600160a01b038216614b1757604051636cd2038560e11b815260040160405180910390fd5b306001600160a01b03831603614b4057604051637e69945160e11b815260040160405180910390fd5b805f03614b605760405163bc25207f60e01b815260040160405180910390fd5b5f614b696142a3565b9050614b7481614f73565b5f614b7e83614437565b90505f614b8e8360010154614437565b905080821115614bbb5760405163e2aaeb7b60e01b81526004810183905260248101829052604401611877565b83836001015f828254614bce9190615bd5565b90915550508254614be9906001600160a01b03168686615013565b846001600160a01b03167f0c9a0dce7b92cf97c29c155081f230310c7fd7ca4f3808bf70d8733f5168950d85604051614c2491815260200190565b60405180910390a25050505050565b5f614c3c6142d7565b6031810154909150610100900460ff1680614c625750602a810154600160e81b900460ff165b80614c7857506038810154600160901b900460ff165b1561257d57604051639de6bad160e01b815260040160405180910390fd5b614ca08282613357565b6112465760405163e2517d3f60e01b81526001600160a01b038216600482015260248101839052604401611877565b7f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f0090565b5f5f614cfd614ccf565b5460021492915050565b5f5f60205f8451602086015f885af180614d26576040513d5f823e3d81fd5b50505f513d91508115614d3d578060011415614d4a565b6001600160a01b0384163b155b15611fbb5783604051635274afe760e01b815260040161187791906155b3565b614d72615044565b61412457604051631afcd79f60e31b815260040160405180910390fd5b6142c7614d6a565b5f5f614da16144db565b9050614dad8484613357565b614e2c575f848152602082815260408083206001600160a01b03871684529091529020805460ff19166001179055614de23390565b6001600160a01b0316836001600160a01b0316857f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a4600191505061127a565b5f91505061127a565b336001600160a01b0382161461257d57604051633ee1754160e21b81526001600160a01b0382166004820152336024820152604401611877565b5f5f614e796144db565b9050614e858484613357565b15614e2c575f848152602082815260408083206001600160a01b0387168085529252808320805460ff1916905551339287917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a4600191505061127a565b614eed612a1c565b61412457604051638dfc202b60e01b815260040160405180910390fd5b5f5f516020615ed15f395f51905f52612589565b614f278261505d565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a2805115614f6b5761130882826150b7565b611246615129565b600181015481546040516370a0823160e01b81525f916001600160a01b0316906370a0823190614fa79030906004016155b3565b602060405180830381865afa158015614fc2573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614fe69190615b6b565b90508082111561130857604051637e81a69560e01b81526004810183905260248101829052604401611877565b6040516001600160a01b0383811660248301526044820183905261130891859182169063a9059cbb90606401614405565b5f61504d614488565b54600160401b900460ff16919050565b806001600160a01b03163b5f036150895780604051634c9c8ce360e01b815260040161187791906155b3565b5f516020615ed15f395f51905f5280546001600160a01b0319166001600160a01b0392909216919091179055565b60605f5f846001600160a01b0316846040516150d39190615eba565b5f60405180830381855af49150503d805f811461510b576040519150601f19603f3d011682016040523d82523d5f602084013e615110565b606091505b5091509150615120858383615148565b95945050505050565b34156141245760405163b398979f60e01b815260040160405180910390fd5b60608261515d576151588261519b565b61159c565b815115801561517457506001600160a01b0384163b155b156151945783604051639996b31560e01b815260040161187791906155b3565b508061159c565b8051156151aa57805160208201fd5b60405163d6bda27560e01b815260040160405180910390fd5b604051806101a001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020016152286040518060c001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f151581525090565b81525f6020820181905260408201819052606082018190526080820181905260a0820181905260c09091015290565b5f60e0828403128015615268575f5ffd5b509092915050565b5f60208284031215615280575f5ffd5b81356001600160e01b03198116811461159c575f5ffd5b5f5f602083850312156152a8575f5ffd5b82356001600160401b038111156152bd575f5ffd5b8301601f810185136152cd575f5ffd5b80356001600160401b038111156152e2575f5ffd5b8560208284010111156152f3575f5ffd5b6020919091019590945092505050565b6001600160a01b038116811461257d575f5ffd5b803561190481615303565b5f5f5f60608486031215615334575f5ffd5b833561533f81615303565b9250602084013561534f81615303565b929592945050506040919091013590565b5f5f5f5f5f60a08688031215615374575f5ffd5b853561537f81615303565b9450602086013561538f81615303565b9350604086013561539f81615303565b925060608601356153af81615303565b915060808601356153bf81615303565b809150509295509295909350565b5f5f604083850312156153de575f5ffd5b50508035926020909101359150565b5f602082840312156153fd575f5ffd5b5035919050565b5f60208284031215615414575f5ffd5b813561159c81615303565b5f5f60408385031215615430575f5ffd5b82359150602083013561544281615303565b809150509250929050565b5f5f5f5f60808587031215615460575f5ffd5b84359350602085013561547281615303565b93969395505050506040820135916060013590565b5f5f5f60608486031215615499575f5ffd5b83359250602084013561534f81615303565b801515811461257d575f5ffd5b5f602082840312156154c8575f5ffd5b813561159c816154ab565b5f610120820190508251825260208301516020830152604083015160408301526001600160401b0360608401511660608301526001600160401b03608084015116608083015260a083015161553360a08401826001600160401b03169052565b5060c083015161554760c084018215159052565b5060e083015161555b60e084018215159052565b5061010083015161402f61010084018215159052565b5f5f82840360c0811215615583575f5ffd5b8335925060a0601f1982011215615598575f5ffd5b506020830190509250929050565b6001600160a01b03169052565b6001600160a01b0391909116815260200190565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f191681016001600160401b0381118282101715615603576156036155c7565b604052919050565b5f6001600160401b03821115615623576156236155c7565b50601f01601f191660200190565b5f5f60408385031215615642575f5ffd5b823561564d81615303565b915060208301356001600160401b03811115615667575f5ffd5b8301601f81018513615677575f5ffd5b803561568a6156858261560b565b6155db565b81815286602083850101111561569e575f5ffd5b816020840160208301375f602083830101528093505050509250929050565b5f5f604083850312156156ce575f5ffd5b82356156d981615303565b946020939093013593505050565b5f5f5f606084860312156156f9575f5ffd5b505081359360208301359350604090920135919050565b60ff8116811461257d575f5ffd5b5f6020828403121561572e575f5ffd5b813561159c81615710565b5f5f82840360e081121561574b575f5ffd5b8335925060c0601f1982011215615598575f5ffd5b81516001600160a01b0390811682526020808401518216908301526040808401518216908301526060808401518216908301526080808401519091169082015260a08281015160e08301916157b7908401826155a6565b5060c083015161402f60c08401826155a6565b5f61012082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260018060a01b0360a08401511660a08301526001600160401b0360c08401511660c083015260e083015161555b60e084018215159052565b602081525f82518060208401528060208501604085015e5f604082850101526040601f19601f83011684010191505092915050565b5f5f6040838503121561587c575f5ffd5b82356156d981615710565b803561ffff81168114611904575f5ffd5b5f5f604083850312156158a9575f5ffd5b6158b283615887565b9150602083013561544281615303565b5f6101208201905082518252602083015160208301526001600160401b03604084015116604083015263ffffffff60608401511660608301526080830151615912608084018263ffffffff169052565b5060a083015160a083015260c083015160c083015260e083015160e083015261010083015161402f61010084018215159052565b5f61024082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c08301516159cd60c0840182805182526020810151602083015260408101516040830152606081015160608301526080810151608083015260a0810151151560a08301525050565b5060e08301516159e16101808401826155a6565b506101008301516159f66101a08401826155a6565b50610120830151615a0b6101c08401826155a6565b506101408301516001600160401b03166101e083015261016083015160ff1661020083015261018083015180151561022084015261402f565b5f5f60408385031215615a55575f5ffd5b823591506020830135615442816154ab565b82815261010081018235615a7a81615303565b6001600160a01b0316602083810191909152830135615a9881615303565b6001600160a01b0316604083810191909152830135615ab681615303565b6001600160a01b0316606083810191909152615ad3908401615317565b615ae060808401826155a6565b50615aed60808401615317565b615afa60a08401826155a6565b50615b0760a08401615317565b615b1460c08401826155a6565b50615b2160c08401615317565b615b2e60e08401826155a6565b509392505050565b83815260406020820152816040820152818360608301375f818301606090810191909152601f909201601f1916010192915050565b5f60208284031215615b7b575f5ffd5b5051919050565b6001600160a01b039384168152919092166020820152604081019190915260600190565b5f60208284031215615bb6575f5ffd5b815161159c816154ab565b634e487b7160e01b5f52601160045260245ffd5b8181038181111561127a5761127a615bc1565b8082018082111561127a5761127a615bc1565b5f60208284031215615c0b575f5ffd5b815161159c81615710565b5f5f60408385031215615c27575f5ffd5b82516020840151909250615442816154ab565b5f60208284031215615c4a575f5ffd5b815161159c81615303565b94855260208501939093526001600160a01b039190911660408401526060830152608082015260a00190565b5f60208284031215615c91575f5ffd5b81516001600160401b03811115615ca6575f5ffd5b8201601f81018413615cb6575f5ffd5b8051615cc46156858261560b565b818152856020838501011115615cd8575f5ffd5b8160208401602083015e5f91810160200191909152949350505050565b803563ffffffff81168114611904575f5ffd5b80356001600160401b0381168114611904575f5ffd5b8381526020810183905260e0810161ffff615d3884615887565b16604083015263ffffffff615d4f60208501615cf5565b1660608301526001600160401b03615d6960408501615d08565b1660808301526001600160401b03615d8360608501615d08565b1660a08301526001600160401b03615d9d60808501615d08565b1660c0830152949350505050565b5f5f60408385031215615dbc575f5ffd5b505080516020909101519092909150565b83815260208101839052610100810161ffff615de884615887565b16604083015261ffff615dfd60208501615887565b16606083015263ffffffff615e1460408501615cf5565b1660808301526001600160401b03615e2e60608501615d08565b1660a08301526001600160401b03615e4860808501615d08565b1660c08301526001600160401b03615e6260a08501615d08565b1660e0830152949350505050565b634e487b7160e01b5f52600160045260245ffd5b808202811582820484141761127a5761127a615bc1565b5f82615eb557634e487b7160e01b5f52601260045260245ffd5b500490565b5f82518060208501845e5f92019182525091905056fe360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc8f949a3ba351e10a4e8a55f43474eba190dceef5961d8b678c89e6dd8f5681ef55435dd261a4b9b3364963f7738a7a662ad9c84396d64be3365284bb7f0a5041a26469706673582212202429b976a2086b53bfda680ca991465ca6d02f6e1652cf2feb7fe7ea9c3a120564736f6c634300081e0033","optimization_enabled":true,"verified_twin_address_hash":null,"is_verified":true,"compiler_settings":{"evmVersion":"cancun","libraries":{"src/ReserveManager.sol:BorrowerPayoutLib":"0x11905fea06726c3cd1d43befd994d11fcce0d79f","src/ReserveManager.sol:ReserveAccrualCreditLib":"0x8aeb59d677899431d029dbc6c8dfc8fad2aeb821","src/ReserveManager.sol:ReserveAccrualLib":"0x8768f6f689d9ba1f0c08d418af8ff31ac820a4a5","src/ReserveManager.sol:ReserveAccrualLifecycleLib":"0xd72860da3bbbc064ba19ac5c8a9e49022b58cdb7","src/ReserveManager.sol:ReserveAccrualServiceLib":"0x662396fdb7220639d61f0491284b5277062c3eeb","src/ReserveManager.sol:ReserveAccrualViewsLib":"0xd999970138c2397ca8582710676a29da5b6da23d","src/ReserveManager.sol:ReserveCascadeLib":"0xa7ea67345ea180ed41093cc6b9660af8a3744913","src/ReserveManager.sol:ReserveCreditLib":"0x6cb6ff7bed904cfdf8da7dc30fd8446ad89d4e05","src/ReserveManager.sol:ReserveIncidentLib":"0x69e62255248a7240fc5189671d20edd1a069e105","src/ReserveManager.sol:ReserveMigrationLib":"0x55cd23031ce9268a19552341d4041530868ae624","src/ReserveManager.sol:ReserveMigrationViewLib":"0x179e54e2096c93bb1c835a9797a5b70946086de9","src/ReserveManager.sol:ReserveRoundingLib":"0x353aea61b5760644560f98c07c56752478ec591d","src/ReserveManager.sol:ReserveWiringLib":"0xe0b4679481e5c355e8fb783aa6c73159bcf6b139"},"metadata":{"bytecodeHash":"ipfs"},"optimizer":{"enabled":true,"runs":100},"remappings":[":@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",":@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",":erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",":forge-std/=lib/forge-std/src/",":halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",":openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",":openzeppelin-contracts/=lib/openzeppelin-contracts/",":solady/=lib/solady/src/"]},"optimization_runs":100,"sourcify_repo_url":"https://repo.sourcify.dev/contracts/partial_match/1/0x99B4DFa4e1344273d5335bD90de1dea3A02b9C3A/","decoded_constructor_args":null,"compiler_version":"0.8.30+commit.73712a01","is_verified_via_verifier_alliance":false,"verified_at":"2026-09-24T00:07:48.871349Z","implementations":[],"proxy_type":null,"external_libraries":[{"name":"src/ReserveManager.sol:BorrowerPayoutLib","address_hash":"0x11905fEA06726C3Cd1d43bEfD994d11fCCe0D79F"},{"name":"src/ReserveManager.sol:ReserveAccrualCreditLib","address_hash":"0x8aeb59d677899431d029dbC6C8dfc8faD2aeb821"},{"name":"src/ReserveManager.sol:ReserveAccrualLib","address_hash":"0x8768f6F689D9ba1F0c08D418aF8fF31ac820a4A5"},{"name":"src/ReserveManager.sol:ReserveAccrualLifecycleLib","address_hash":"0xD72860da3bbBC064ba19AC5C8a9e49022b58cdb7"},{"name":"src/ReserveManager.sol:ReserveAccrualServiceLib","address_hash":"0x662396fDb7220639d61f0491284b5277062C3EEB"},{"name":"src/ReserveManager.sol:ReserveAccrualViewsLib","address_hash":"0xd999970138C2397CA8582710676a29Da5b6dA23d"},{"name":"src/ReserveManager.sol:ReserveCascadeLib","address_hash":"0xA7eA67345ea180ED41093cC6B9660AF8a3744913"},{"name":"src/ReserveManager.sol:ReserveCreditLib","address_hash":"0x6CB6FF7BeD904Cfdf8DA7DC30fd8446ad89d4e05"},{"name":"src/ReserveManager.sol:ReserveIncidentLib","address_hash":"0x69E62255248a7240fc5189671D20edD1a069E105"},{"name":"src/ReserveManager.sol:ReserveMigrationLib","address_hash":"0x55cD23031ce9268A19552341D4041530868ae624"},{"name":"src/ReserveManager.sol:ReserveMigrationViewLib","address_hash":"0x179E54e2096c93BB1c835a9797a5B70946086De9"},{"name":"src/ReserveManager.sol:ReserveRoundingLib","address_hash":"0x353AEa61B5760644560f98c07c56752478eC591d"},{"name":"src/ReserveManager.sol:ReserveWiringLib","address_hash":"0xE0B4679481e5c355E8fb783AA6C73159BCf6B139"}],"creation_bytecode":"0x60a060405230608052348015610013575f5ffd5b5061001c610021565b6100d3565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00805468010000000000000000900460ff16156100715760405163f92ee8a960e01b815260040160405180910390fd5b80546001600160401b03908116146100d05780546001600160401b0319166001600160401b0390811782556040519081527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50565b608051615f666100f95f395f818161460b0152818161463401526147b50152615f665ff3fe60806040526004361061056a575f3560e01c80636af2fa06116102c5578063a895132011610176578063d0a6c794116100d4578063e84b51b91161008e578063e84b51b9146110ba578063ea613780146110d9578063eed8f72e146110ed578063f20b27591461110c578063f604c6df14611120578063f646f35f14611134578063fa7c427414611153575f5ffd5b8063d0a6c79414610ff0578063d141b0b014611004578063d547741f14611025578063d8b080c014611044578063d91e2d2614611063578063e2d252ad14611099575f5ffd5b8063b00424a611610130578063b00424a614610f41578063b1a8255a14610f60578063b54a151b14610d24578063b598401614610f7f578063bace10d114610f93578063c03ab92614610fb2578063ca258c9f14610fd1575f5ffd5b8063a895132014610e7f578063aae98a3814610e9e578063acbe8c3b14610ebd578063ad3cb1cc14610ed1578063ad95d8b614610f0e578063addabaea14610f22575f5ffd5b806389062cb91161022357806398ca56d8116101dd57806398ca56d814610db257806399f39ee114610dd15780639c13906d14610df05780639d2fae9b14610e0f5780639ead894414610e2e578063a217fddf14610e4d578063a5b6e52614610e60575f5ffd5b806389062cb914610d2457806391d1485414610d3857806394ac4bc114610d575780639655804e14610d6b57806397a298ad14610d7f57806397e1594e14610d93575f5ffd5b806376cfbb621161027f57806376cfbb6214610c3b57806376f830f014610c5a57806379a5027814610ca85780638456cb5914610cc95780638671a30114610cdd57806387f0f89a14610cfc5780638849837a14610d10575f5ffd5b80636af2fa0614610ba05780636c01c6da14610bb45780636fa4a33b14610bd357806370db380314610be7578063724f3d6914610bfb57806372790b3314610c1a575f5ffd5b806331e7a70f1161041f578063412838361161037d57806356b22bf21161033757806356b22bf214610add5780635c975abb14610afc57806363874b5814610b105780636616b01214610b2f5780636777079e14610b4357806367d2cd3d14610b6257806369249e5614610b81575f5ffd5b80634128383614610a5b578063431ecf5714610a6f5780634d7eb7a514610a835780634f1ef28614610a9757806352d1902d14610aaa5780635594d46f14610abe575f5ffd5b806336568abe116103d957806336568abe14610978578063366f124e1461099757806339d4bc94146109b65780633e413bee146109d55780633f29aa55146109f65780633f4ba83a14610a2857806340eadce814610a3c575f5ffd5b806331e7a70f146108a7578063334b7433146108c657806333810370146108e557806334ec2d411461090e5780633542b86a1461092d5780633575c7c41461094c575f5ffd5b806312851215116104cc578063248a9ca311610486578063248a9ca3146107a95780632a2061a7146107c85780632ab23cf3146107f75780632f2ff15d1461082b5780632fc3aadd1461084a5780633083b4e51461086957806331bb795c14610888575f5ffd5b806312851215146106fa5780631459457a1461070e578063167832561461072d5780631ca4ee241461074c5780631e5ca8891461076b578063215fc5691461078a575f5ffd5b806308d6b1241161052857806308d6b1241461062c5780630973f3151461064b5780630adc4b6c1461066a5780630c47d267146106895780630efec40c146106a85780630f6018c7146106c757806311af8243146106e6575f5ffd5b8062d91f4a1461056e57806301ffc9a71461058f57806302a24329146105c357806302df9274146105e25780630610ae1414610604578063065f2bfc14610618575b5f5ffd5b348015610579575f5ffd5b5061058d610588366004615257565b6111c0565b005b34801561059a575f5ffd5b506105ae6105a9366004615270565b61124a565b60405190151581526020015b60405180910390f35b3480156105ce575f5ffd5b5061058d6105dd366004615297565b611280565b3480156105ed575f5ffd5b506105f661130d565b6040519081526020016105ba565b34801561060f575f5ffd5b506105f661139a565b348015610623575f5ffd5b506105ae6113ac565b348015610637575f5ffd5b506105ae610646366004615322565b61151d565b348015610656575f5ffd5b5061058d610665366004615360565b6115a3565b348015610675575f5ffd5b5061058d6106843660046153cd565b611659565b348015610694575f5ffd5b506105f66106a33660046153ed565b6116ec565b3480156106b3575f5ffd5b506105f66106c23660046153ed565b611909565b3480156106d2575f5ffd5b506105f66106e13660046153ed565b6119a4565b3480156106f1575f5ffd5b506105f66119c0565b348015610705575f5ffd5b506105f66119d5565b348015610719575f5ffd5b5061058d610728366004615360565b611a1d565b348015610738575f5ffd5b5061058d610747366004615404565b611cda565b348015610757575f5ffd5b5061058d6107663660046153ed565b611d6d565b348015610776575f5ffd5b5061058d6107853660046153ed565b611d86565b348015610795575f5ffd5b506105ae6107a43660046153ed565b611e43565b3480156107b4575f5ffd5b506105f66107c33660046153ed565b611eb7565b3480156107d3575f5ffd5b506107dc611ed5565b604080519384526020840192909252908201526060016105ba565b348015610802575f5ffd5b506108166108113660046153ed565b611efd565b604080519283529015156020830152016105ba565b348015610836575f5ffd5b5061058d61084536600461541f565b611f9f565b348015610855575f5ffd5b5061058d6108643660046153cd565b611fc1565b348015610874575f5ffd5b5061058d610883366004615404565b61204c565b348015610893575f5ffd5b5061058d6108a23660046153ed565b6120d4565b3480156108b2575f5ffd5b506105f66108c136600461544d565b61212f565b3480156108d1575f5ffd5b5061058d6108e0366004615487565b6121d7565b3480156108f0575f5ffd5b506108f96122a1565b604080519283526020830191909152016105ba565b348015610919575f5ffd5b5061058d6109283660046154b8565b6122c1565b348015610938575f5ffd5b506105f66109473660046153ed565b61232a565b348015610957575f5ffd5b5061096b6109663660046153ed565b6123b9565b6040516105ba91906154d3565b348015610983575f5ffd5b5061058d61099236600461541f565b61247b565b3480156109a2575f5ffd5b5061058d6109b1366004615571565b6124ae565b3480156109c1575f5ffd5b5061058d6109d03660046153ed565b6124f8565b3480156109e0575f5ffd5b506109e9612580565b6040516105ba91906155b3565b348015610a01575f5ffd5b507f17085a5db666070eb4aa0aac3c233b268ac6d0b0c76e1646dbb52fd255f00c056105f6565b348015610a33575f5ffd5b5061058d612598565b348015610a47575f5ffd5b506105f6610a563660046153ed565b6125bf565b348015610a66575f5ffd5b5061058d6125f9565b348015610a7a575f5ffd5b506107dc61264d565b348015610a8e575f5ffd5b506109e96126f3565b61058d610aa5366004615631565b61270e565b348015610ab5575f5ffd5b506105f6612729565b348015610ac9575f5ffd5b506105f6610ad83660046153ed565b612745565b348015610ae8575f5ffd5b506105f6610af73660046156bd565b61277f565b348015610b07575f5ffd5b506105ae612a1c565b348015610b1b575f5ffd5b5061058d610b2a3660046156e7565b612a30565b348015610b3a575f5ffd5b506109e9612c1c565b348015610b4e575f5ffd5b506108f9610b5d36600461571e565b612c37565b348015610b6d575f5ffd5b506105f6610b7c36600461544d565b612cc9565b348015610b8c575f5ffd5b5061058d610b9b3660046153cd565b612d9a565b348015610bab575f5ffd5b506105f6612e56565b348015610bbf575f5ffd5b5061058d610bce366004615739565b612e68565b348015610bde575f5ffd5b506105f6612eb2565b348015610bf2575f5ffd5b5061058d612f06565b348015610c06575f5ffd5b506105f6610c153660046153cd565b612f72565b348015610c25575f5ffd5b50610c2e613023565b6040516105ba9190615760565b348015610c46575f5ffd5b5061058d610c553660046153cd565b6130a4565b348015610c65575f5ffd5b50610c6e6130d8565b604080516001600160a01b03968716815294861660208601529285169284019290925283166060830152909116608082015260a0016105ba565b348015610cb3575f5ffd5b50610cbc613124565b6040516105ba91906157ca565b348015610cd4575f5ffd5b5061058d6131c9565b348015610ce8575f5ffd5b506105f6610cf73660046153ed565b6131f0565b348015610d07575f5ffd5b506105f6613228565b348015610d1b575f5ffd5b506105f6613323565b348015610d2f575f5ffd5b506105ae613346565b348015610d43575f5ffd5b506105ae610d5236600461541f565b613357565b348015610d62575f5ffd5b506105f661338b565b348015610d76575f5ffd5b5061058d61339d565b348015610d8a575f5ffd5b506109e96133ef565b348015610d9e575f5ffd5b5061058d610dad3660046156e7565b61345b565b348015610dbd575f5ffd5b5061058d610dcc366004615404565b613588565b348015610ddc575f5ffd5b5061058d610deb3660046153ed565b6135bc565b348015610dfb575f5ffd5b506105f6610e0a3660046153ed565b6135e6565b348015610e1a575f5ffd5b506105f6610e293660046153cd565b613602565b348015610e39575f5ffd5b506108f9610e483660046156e7565b6136f5565b348015610e58575f5ffd5b506105f65f81565b348015610e6b575f5ffd5b5061058d610e7a3660046153ed565b613ab6565b348015610e8a575f5ffd5b5061058d610e993660046153cd565b613ae0565b348015610ea9575f5ffd5b5061058d610eb83660046153ed565b613b6a565b348015610ec8575f5ffd5b506105f6613b9e565b348015610edc575f5ffd5b50610f01604051806040016040528060058152602001640352e302e360dc1b81525081565b6040516105ba9190615836565b348015610f19575f5ffd5b506105f6613bb0565b348015610f2d575f5ffd5b506105f6610f3c36600461586b565b613c56565b348015610f4c575f5ffd5b506105ae610f5b3660046153ed565b613cd3565b348015610f6b575f5ffd5b5061058d610f7a366004615898565b613cf2565b348015610f8a575f5ffd5b506105f6613d59565b348015610f9e575f5ffd5b506108f9610fad3660046153ed565b613d6b565b348015610fbd575f5ffd5b506105f6610fcc3660046153ed565b613e1d565b348015610fdc575f5ffd5b5061058d610feb3660046156bd565b613e27565b348015610ffb575f5ffd5b506105f6613e7b565b34801561100f575f5ffd5b50611018613ec9565b6040516105ba91906158c2565b348015611030575f5ffd5b5061058d61103f36600461541f565b613f6f565b34801561104f575f5ffd5b506105f661105e3660046153cd565b613f8b565b34801561106e575f5ffd5b50611077614036565b60408051948552602085019390935291830152151560608201526080016105ba565b3480156110a4575f5ffd5b506110ad614083565b6040516105ba9190615946565b3480156110c5575f5ffd5b5061058d6110d4366004615a44565b6140d4565b3480156110e4575f5ffd5b5061058d61411c565b3480156110f8575f5ffd5b506105f66111073660046153ed565b614126565b348015611117575f5ffd5b506105ae614151565b34801561112b575f5ffd5b5061058d614166565b34801561113f575f5ffd5b5061058d61114e3660046153cd565b6141ce565b34801561115e575f5ffd5b5061117261116d3660046153ed565b614202565b6040516105ba91905f60a08201905082518252602083015160208301526001600160401b03604084015116604083015260608301511515606083015260808301511515608083015292915050565b5f6111ca81614264565b6111d261426e565b738768f6f689d9ba1f0c08d418af8ff31ac820a4a563715870ff6111f46142a3565b846040518363ffffffff1660e01b8152600401611212929190615a67565b5f6040518083038186803b158015611228575f5ffd5b505af415801561123a573d5f5f3e3d5ffd5b505050506112466142c7565b5050565b5f6001600160e01b03198216637965db0b60e01b148061127a57506301ffc9a760e01b6001600160e01b03198316145b92915050565b5f61128a81614264565b61129261426e565b7355cd23031ce9268a19552341d4041530868ae624639e1d1d216112b46142a3565b85856040518463ffffffff1660e01b81526004016112d493929190615b36565b5f6040518083038186803b1580156112ea575f5ffd5b505af41580156112fc573d5f5f3e3d5ffd5b505050506113086142c7565b505050565b5f73d999970138c2397ca8582710676a29da5b6da23d6385ef8b796113306142a3565b6040516001600160e01b031960e084901b16815260048101919091525f60248201526044015b602060405180830381865af4158015611371573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113959190615b6b565b905090565b5f6113a36142d7565b60370154905090565b5f5f6113b66142a3565b905080601801545f1415806113ce5750600681015415155b156113db57600191505090565b60088101541515806113f05750601281015415155b806113fe5750601b81015415155b1561140b57600191505090565b611414816142fb565b1561142157600191505090565b60058101546001600160a01b0316801580611447575060048201546001600160a01b0316155b156114555760019250505090565b806001600160a01b0316630e9141926040518163ffffffff1660e01b8152600401602060405180830381865afa158015611491573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114b59190615b6b565b816001600160a01b0316632f6b1f626040518163ffffffff1660e01b8152600401602060405180830381865afa1580156114f1573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115159190615b6b565b119250505090565b6040516302167b9760e41b81525f9073353aea61b5760644560f98c07c56752478ec591d90632167b9709061155a90879087908790600401615b82565b602060405180830381865af4158015611575573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115999190615ba6565b90505b9392505050565b6115ab614390565b5f6115b581614264565b73e0b4679481e5c355e8fb783aa6c73159bcf6b1396316b5eeb76115d76142a3565b6040516001600160e01b031960e084901b16815260048101919091526001600160a01b03808a166024830152808916604483015280881660648301528087166084830152851660a482015260c4015f6040518083038186803b15801561163b575f5ffd5b505af415801561164d573d5f5f3e3d5ffd5b50505050505050505050565b611661614390565b5f61166b81614264565b7369e62255248a7240fc5189671d20edd1a069e105638e348b3c61168d6142a3565b6040516001600160e01b031960e084901b168152600481019190915260248101869052604481018590526064015b5f6040518083038186803b1580156116d1575f5ffd5b505af41580156116e3573d5f5f3e3d5ffd5b50505050505050565b5f6116f5614390565b6116fd61426e565b815f0361171d5760405163bc25207f60e01b815260040160405180910390fd5b5f6117266142a3565b80546040516370a0823160e01b81529192505f916001600160a01b03909116906370a082319061175a9030906004016155b3565b602060405180830381865afa158015611775573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117999190615b6b565b82549091506117b3906001600160a01b03163330876143dd565b81546040516370a0823160e01b81525f9183916001600160a01b03909116906370a08231906117e69030906004016155b3565b602060405180830381865afa158015611801573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906118259190615b6b565b61182f9190615bd5565b9050805f0361185157604051630255c60b60e11b815260040160405180910390fd5b84811461188057604051634953408b60e01b815260048101869052602481018290526044015b60405180910390fd5b80836001015f8282546118939190615be8565b909155506118a2905081614437565b9350337fdfe70afea21e3db591383c6e83d6952e0120f6f10e7dd6be79b3fbd2647590fa82866118d187614447565b600888015460408051948552602085019390935291830152606082015260800160405180910390a25050506119046142c7565b919050565b5f61191261426e565b73662396fdb7220639d61f0491284b5277062c3eeb63f7aa64156119346142a3565b846040518363ffffffff1660e01b815260040161195b929190918252602082015260400190565b602060405180830381865af4158015611976573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061199a9190615b6b565b90506119046142c7565b5f6119ad6142a3565b5f928352601a0160205250604090205490565b5f6113956119cc6142a3565b60010154614437565b5f738aeb59d677899431d029dbc6c8dfc8fad2aeb82163c92c9bdb6040518163ffffffff1660e01b8152600401602060405180830381865af4158015611371573d5f5f3e3d5ffd5b5f611a26614488565b805490915060ff600160401b82041615906001600160401b03165f81158015611a4c5750825b90505f826001600160401b03166001148015611a675750303b155b905081158015611a75575080155b15611a935760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff191660011785558315611abd57845460ff60401b1916600160401b1785555b6001600160a01b038a161580611ada57506001600160a01b038916155b80611aec57506001600160a01b038816155b80611afe57506001600160a01b038716155b80611b1057506001600160a01b038616155b15611b2e57604051636cd2038560e11b815260040160405180910390fd5b5f866001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b6b573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611b8f9190615bfb565b90508060ff16600614611bba57604051632902554b60e21b815260ff82166004820152602401611877565b611bc26144b0565b611bca6144b0565b611bd26144b8565b611bda6144b0565b611be45f8c6144c8565b50611c0f7fcb6c915afba301a06d8c17327f1f6eec8e262e5feb9a4db38c9ac4d14eb366a38b6144c8565b50611c275f516020615f115f395f51905f528a6144c8565b50611c527f189ab7a9244df0848122154315af71fe140f3db0fe014031783b0946b8c9d2e3896144c8565b505f611c5c6142a3565b80546001600160a01b038a166001600160a01b0319909116178155601601805461ff0019166101001790555050831561164d57845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a150505050505050505050565b611ce2614390565b5f611cec81614264565b73e0b4679481e5c355e8fb783aa6c73159bcf6b13963d015a196611d0e6142a3565b6040516001600160e01b031960e084901b16815260048101919091526001600160a01b03851660248201526044015b5f6040518083038186803b158015611d53575f5ffd5b505af4158015611d65573d5f5f3e3d5ffd5b505050505050565b60405163b7b6414d60e01b815260040160405180910390fd5b611d8e614390565b5f611d976142a3565b60048101549091506001600160a01b03163314611dc957336040516309660a1360e11b815260040161187791906155b3565b815f03611de95760405163bc25207f60e01b815260040160405180910390fd5b5f8282601d0154611dfa9190615be8565b601d830181905560408051858152602081018390529192507fb92037a3944a13f75b8b303a4c2d15d6deac77392612e3ddc826aa1dc6b5092591015b60405180910390a1505050565b6040516342b84e3160e11b8152600481018290525f9073662396fdb7220639d61f0491284b5277062c3eeb906385709c6290602401602060405180830381865af4158015611e93573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061127a9190615ba6565b5f5f611ec16144db565b5f9384526020525050604090206001015490565b5f5f5f5f611ee16142a3565b6010810154601182015460129092015490969195509350915050565b5f5f611f0761426e565b738aeb59d677899431d029dbc6c8dfc8fad2aeb821637bc951eb611f296142a3565b856040518363ffffffff1660e01b8152600401611f50929190918252602082015260400190565b6040805180830381865af4158015611f6a573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f8e9190615c16565b91509150611f9a6142c7565b915091565b611fa882611eb7565b611fb181614264565b611fbb83836144c8565b50505050565b611fc9614390565b5f516020615ef15f395f51905f52611fe081614264565b611fe86144ff565b611ff183614525565b736cb6ff7bed904cfdf8da7dc30fd8446ad89d4e056341c81f076120136142a3565b6040516001600160e01b031960e084901b16815260048101919091526024810186905260448101859052600160648201526084016116bb565b612054614390565b5f61205e81614264565b6040516381bac14f60e01b81527311905fea06726c3cd1d43befd994d11fcce0d79f906381bac14f906120959085906004016155b3565b602060405180830381865af41580156120b0573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113089190615c3a565b6120dc614390565b5f6120e681614264565b7369e62255248a7240fc5189671d20edd1a069e10563f5ed77e76121086142a3565b846040518363ffffffff1660e01b8152600401611d3d929190918252602082015260400190565b5f61213861426e565b6121406144ff565b73d72860da3bbbc064ba19ac5c8a9e49022b58cdb763344627156121626142a3565b878787876040518663ffffffff1660e01b8152600401612186959493929190615c55565b602060405180830381865af41580156121a1573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906121c59190615b6b565b90506121cf6142c7565b949350505050565b6121df614390565b5f516020615ef15f395f51905f526121f681614264565b6121fe61426e565b6122066144ff565b61220f84614525565b736cb6ff7bed904cfdf8da7dc30fd8446ad89d4e05630f1d41076122316142a3565b6040516001600160e01b031960e084901b1681526004810191909152602481018790526001600160a01b0386166044820152606481018590526084015f6040518083038186803b158015612283575f5ffd5b505af4158015612295573d5f5f3e3d5ffd5b50505050611fbb6142c7565b5f5f5f6122ac6142a3565b90508060060154816007015492509250509091565b6122c9614390565b5f6122d381614264565b5f6122dc6142a3565b6016810180548515156101000261ff00199091161790556040519091507f3e1d16535c5af6624bc3d6b81a0d9c551d9b46bd3c8f17301dda39f69fb22a2990611e3690851515815260200190565b5f73d999970138c2397ca8582710676a29da5b6da23d6356a75db461234d6142a3565b6040516001600160e01b031960e084901b1681526004810191909152602481018590525f60448201526064015b602060405180830381865af4158015612395573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061127a9190615b6b565b60408051610120810182525f80825260208201819052818301819052606082018190526080820181905260a0820181905260c0820181905260e0820181905261010082015290516303c0053960e31b8152600481018390526119049073d999970138c2397ca8582710676a29da5b6da23d90631e0029c8906024015b5f60405180830381865af415801561244f573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526124769190810190615c81565b61458f565b6001600160a01b03811633146124a45760405163334bd91960e11b815260040160405180910390fd5b6113088282614597565b6124b661426e565b73d72860da3bbbc064ba19ac5c8a9e49022b58cdb763c8a47fcf6124d86142a3565b84846040518463ffffffff1660e01b815260040161121293929190615d1e565b61250061426e565b738aeb59d677899431d029dbc6c8dfc8fad2aeb821635d08936b6125226142a3565b836040518363ffffffff1660e01b8152600401612549929190918252602082015260400190565b5f6040518083038186803b15801561255f575f5ffd5b505af4158015612571573d5f5f3e3d5ffd5b5050505061257d6142c7565b50565b5f6125896142a3565b546001600160a01b0316919050565b6125a0614390565b5f516020615f115f395f51905f526125b781614264565b61257d6145aa565b604051632e3959db60e11b8152600481018290525f9073d999970138c2397ca8582710676a29da5b6da23d90635c72b3b69060240161237a565b738768f6f689d9ba1f0c08d418af8ff31ac820a4a5633dae371f6040518163ffffffff1660e01b81526004015f6040518083038186803b15801561263b575f5ffd5b505af4158015611fbb573d5f5f3e3d5ffd5b5f5f5f5f6126596142a3565b600181015481546040516370a0823160e01b81529196509192506001600160a01b03909116906370a08231906126939030906004016155b3565b602060405180830381865afa1580156126ae573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906126d29190615b6b565b92508284116126e1575f6126eb565b6126eb8385615bd5565b915050909192565b5f6126fc6142a3565b600501546001600160a01b0316919050565b612716614600565b61271f8261468e565b61124682826146f7565b5f6127326147aa565b505f516020615ed15f395f51905f525b90565b604051630bd30f1160e01b8152600481018290525f90738aeb59d677899431d029dbc6c8dfc8fad2aeb82190630bd30f119060240161237a565b5f612788614390565b61279061426e565b6127986144ff565b6127c27f7b765e0e932d348852a6f810bfa1ab891e259123f02db8cdcde614c57022335733613357565b1580156127e357506127e15f516020615ef15f395f51905f5233613357565b155b156128035733604051631d4a04d360e21b815260040161187791906155b3565b6001600160a01b03831661282a57604051636cd2038560e11b815260040160405180910390fd5b815f0361284a5760405163bc25207f60e01b815260040160405180910390fd5b5f6128536142a3565b80546040516370a0823160e01b81529192505f916001600160a01b03909116906370a08231906128879030906004016155b3565b602060405180830381865afa1580156128a2573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128c69190615b6b565b82549091506128e0906001600160a01b03168630876143dd565b81546040516370a0823160e01b81525f9183916001600160a01b03909116906370a08231906129139030906004016155b3565b602060405180830381865afa15801561292e573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129529190615b6b565b61295c9190615bd5565b9050805f0361297e57604051630255c60b60e11b815260040160405180910390fd5b8481146129a857604051634953408b60e01b81526004810186905260248101829052604401611877565b80836001015f8282546129bb9190615be8565b909155506129ca905081614437565b60408051878152602081018390529195506001600160a01b038816917fdf761661d51ab4147355430c8891e0dc7406b6aece4d2b564ccd87e0baa6dfd9910160405180910390a250505061127a6142c7565b5f5f612a266147f3565b5460ff1692915050565b612a38614390565b5f612a4281614264565b825f03612a625760405163bc25207f60e01b815260040160405180910390fd5b81612a805760405163557b260d60e11b815260040160405180910390fd5b5f612a896142a3565b9050612a936142d7565b6031015460ff1615612b1a576040516318b46b2160e31b81526004810182905260248101869052738aeb59d677899431d029dbc6c8dfc8fad2aeb8219063c5a3590890604401602060405180830381865af4158015612af4573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612b189190615b6b565b505b5f858152601c820160209081526040808320546003850190925290912054612b428282615bd5565b861115612b7f578686612b558484615bd5565b60405163770505cd60e01b8152600481019390935260248301919091526044820152606401611877565b5f612b8a8784615be8565b5f898152601c860160205260408120829055601b86015491925090612bb0908990615be8565b601b86018190559050887fb0974ca28c96a4d84cc3a64f95269c76ed8bf8728dac225d424fe4e29d5c38f5898484612be78a614447565b604080519485526020850193909352918301526060820152608081018a905260a00160405180910390a2505050505050505050565b5f612c256142a3565b600401546001600160a01b0316919050565b5f5f612c4161426e565b738768f6f689d9ba1f0c08d418af8ff31ac820a4a5633f9d84ed612c636142a3565b6040516001600160e01b031960e084901b168152600481019190915260ff861660248201526044016040805180830381865af4158015612ca5573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f8e9190615dab565b5f612cd2614390565b5f516020615ef15f395f51905f52612ce981614264565b612cf161426e565b612cf96144ff565b612d0286614817565b736cb6ff7bed904cfdf8da7dc30fd8446ad89d4e0563d7f91645612d246142a3565b888888886040518663ffffffff1660e01b8152600401612d48959493929190615c55565b602060405180830381865af4158015612d63573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612d879190615b6b565b9150612d916142c7565b50949350505050565b612da2614390565b5f516020615ef15f395f51905f52612db981614264565b612dc16142d7565b6031015460ff1615612e3457604051635bd45aa160e01b8152600481018490526024810183905273d72860da3bbbc064ba19ac5c8a9e49022b58cdb790635bd45aa1906044015f6040518083038186803b158015612e1d575f5ffd5b505af4158015612e2f573d5f5f3e3d5ffd5b505050505b736cb6ff7bed904cfdf8da7dc30fd8446ad89d4e0563b430b40261168d6142a3565b5f612e5f6142a3565b60010154905090565b612e7061426e565b73d72860da3bbbc064ba19ac5c8a9e49022b58cdb763d243be1a612e926142a3565b84846040518463ffffffff1660e01b815260040161121293929190615dcd565b5f73d999970138c2397ca8582710676a29da5b6da23d6356a75db4612ed56142a3565b6040516001600160e01b031960e084901b16815260048101919091525f602482015260016044820152606401611356565b612f0e614390565b5f612f176142d7565b603181015490915060ff1680612f3857506038810154600160901b900460ff165b80612f465750603281015415155b80612f545750603781015415155b1561257d57604051632e8a9a8760e11b815260040160405180910390fd5b5f612f7b614390565b612f8361426e565b612f8b614847565b7369e62255248a7240fc5189671d20edd1a069e105636d6259d4612fad6142a3565b6040516001600160e01b031960e084901b16815260048101919091526024810186905260448101859052606401602060405180830381865af4158015612ff5573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130199190615b6b565b905061127a6142c7565b6040805160e0810182525f80825260208201819052918101829052606081018290526080810182905260a0810182905260c0810191909152612742738768f6f689d9ba1f0c08d418af8ff31ac820a4a563ab87e6096040518163ffffffff1660e01b81526004015f60405180830381865af415801561244f573d5f5f3e3d5ffd5b6130ac614390565b5f6130b681614264565b7369e62255248a7240fc5189671d20edd1a069e1056329b8cfc761168d6142a3565b5f5f5f5f5f5f6130e66142a3565b600a810154600b820154600c830154600e840154600f909401546001600160a01b039384169b9284169a509083169850928216965091169350915050565b6131806040518061012001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f6001600160a01b031681526020015f6001600160401b031681526020015f151581526020015f151581525090565b612742738768f6f689d9ba1f0c08d418af8ff31ac820a4a5636666d3726040518163ffffffff1660e01b81526004015f60405180830381865af415801561244f573d5f5f3e3d5ffd5b6131d1614390565b5f516020615f115f395f51905f526131e881614264565b61257d614890565b5f5f6131fb836148d6565b90508261320782614437565b1461127a57604051630684073360e21b815260048101849052602401611877565b5f613231614390565b61323961426e565b5f6132426142a3565b80546040516370a0823160e01b81529192505f916001600160a01b03909116906370a08231906132769030906004016155b3565b602060405180830381865afa158015613291573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906132b59190615b6b565b60018301549091508181116132ca575f6132d4565b6132d48282615bd5565b60408051838152602081018590529081018290529094507f4b9a8f42a44d48811eb4258375f7eb86085ce952140b71df79c426efc09733b39060600160405180910390a15050506127426142c7565b5f5f6133356133306142a3565b6142fb565b905061334081614437565b91505090565b5f6113956133526142a3565b6148e6565b5f5f6133616144db565b5f948552602090815260408086206001600160a01b03959095168652939052505090205460ff1690565b5f6133946142a3565b601d0154905090565b5f6133a781614264565b6133af61426e565b738768f6f689d9ba1f0c08d418af8ff31ac820a4a563869467c96133d16142a3565b6040518263ffffffff1660e01b815260040161254991815260200190565b5f7311905fea06726c3cd1d43befd994d11fcce0d79f637b1039996040518163ffffffff1660e01b8152600401602060405180830381865af4158015613437573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113959190615c3a565b613463614390565b5f61346d81614264565b825f0361348d5760405163bc25207f60e01b815260040160405180910390fd5b816134ab5760405163557b260d60e11b815260040160405180910390fd5b5f6134b46142a3565b5f868152601c82016020526040902054909150808511156134f95760405163d1eaa8e160e01b8152600481018790526024810186905260448101829052606401611877565b5f6135048683615bd5565b5f888152601c850160205260408120829055601b8501549192509061352a908890615bd5565b601b850181905560408051898152602081018590529081018290526060810188905290915088907f3ab57d7bbb971777f2c003e6062120261bd37627de94c0cf82109c6593c478849060800160405180910390a25050505050505050565b613590614390565b5f61359a81614264565b73e0b4679481e5c355e8fb783aa6c73159bcf6b1396307373853611d0e6142a3565b6135c461426e565b73d72860da3bbbc064ba19ac5c8a9e49022b58cdb7634d23e1dc6125226142a3565b5f6135ef6142a3565b5f928352601c0160205250604090205490565b5f61360b614390565b5f6136146142a3565b60048101549091506001600160a01b0316331461364657336040516309660a1360e11b815260040161187791906155b3565b601d8101545f81900361365d575f9250505061127a565b5f858152601c83016020526040902054848111156136785750835b8082106136855780613687565b815b9350835f0361369b575f935050505061127a565b5f6136a68584615bd5565b601d8501819055604080518781526020810183905291925088917f59579095e479f9ef696f9072e4c489cde86b02eda5cd00218e3862081081a1dd910160405180910390a25050505092915050565b5f5f6136ff614390565b61370761426e565b61370f614847565b5f6137186142a3565b90505f6137258288614a4c565b6019830154909150868114613757576040516355046ad760e11b81526004810182905260248101889052604401611877565b5f613761846142fb565b9050805f0361378257604051626b8a0360e31b815260040160405180910390fd5b61378b81614437565b9450868511156137b85760405163083e7d8160e11b81526004810186905260248101889052604401611877565b6137c183614a9c565b95506137d186600160ff1b111590565b6137dd576137dd615e70565b60068401545f819003613882575f87815260098601602052604090205460ff161561381e57604051631902098360e21b815260048101889052602401611877565b5f87815260098601602052604090819020805460ff191660011790556006860188905551849088907fc14b7ab566185952b484a6411b322acff0571957630185c0a7008dcfee38b99b90613875908d815260200190565b60405180910390a36138ac565b8681146138ac576040516308208cab60e21b81526004810182905260248101889052604401611877565b600785018990555f848152601a86016020526040812080548492906138d2908490615be8565b9091555050604051634c1c05b760e11b815260048101869052738768f6f689d9ba1f0c08d418af8ff31ac820a4a5906398380b6e906024015f6040518083038186803b158015613920575f5ffd5b505af4158015613932573d5f5f3e3d5ffd5b505060405163ba19528f60e01b815260048101889052602481018590526044810189905273a7ea67345ea180ed41093cc6b9660af8a3744913925063ba19528f91506064015f6040518083038186803b15801561398d575f5ffd5b505af415801561399f573d5f5f3e3d5ffd5b5050505084601201545f14613a155760405163034cd85160e11b8152600481018690526024810188905273a7ea67345ea180ed41093cc6b9660af8a374491390630699b0a2906044015f6040518083038186803b1580156139fe575f5ffd5b505af4158015613a10573d5f5f3e3d5ffd5b505050505b7fb5a35ece8924c9d143ef885d113989a1896eb4898e6fe7f72eb5e5648911e55686613a448760010154614437565b6040805192835260208301919091520160405180910390a160408051898152602081018890529081018a9052879085907f9a634e851f7a67ae03554fc3908ef8330b3742193155bc9c3d70728ac7c6e9ac9060600160405180910390a35050505050613aae6142c7565b935093915050565b613abe61426e565b73d72860da3bbbc064ba19ac5c8a9e49022b58cdb76323e0b66a6125226142a3565b613ae8614390565b5f516020615ef15f395f51905f52613aff81614264565b613b076144ff565b613b1083614817565b736cb6ff7bed904cfdf8da7dc30fd8446ad89d4e056341c81f07613b326142a3565b6040516001600160e01b031960e084901b168152600481019190915260248101869052604481018590525f60648201526084016116bb565b613b72614390565b5f613b7c81614264565b7369e62255248a7240fc5189671d20edd1a069e1056325269b836121086142a3565b5f613ba76142a3565b60080154905090565b5f5f613bba6142a3565b80546040516370a0823160e01b81529192505f916001600160a01b03909116906370a0823190613bee9030906004016155b3565b602060405180830381865afa158015613c09573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613c2d9190615b6b565b905081600101548111613c40575f613c4f565b6001820154613c4f9082615bd5565b9250505090565b604051633879345760e01b815260ff83166004820152602481018290525f90738aeb59d677899431d029dbc6c8dfc8fad2aeb82190633879345790604401602060405180830381865af4158015613caf573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061159c9190615b6b565b5f613cdc6142a3565b5f92835260090160205250604090205460ff1690565b613cfa61426e565b738768f6f689d9ba1f0c08d418af8ff31ac820a4a563c26c07cd613d1c6142a3565b6040516001600160e01b031960e084901b168152600481019190915261ffff851660248201526001600160a01b0384166044820152606401611212565b5f613d626142a3565b601b0154905090565b5f5f613d75614390565b5f516020615f115f395f51905f52613d8c81614264565b7369e62255248a7240fc5189671d20edd1a069e1056385f92f7f613dae6142a3565b866040518363ffffffff1660e01b8152600401613dd5929190918252602082015260400190565b6040805180830381865af4158015613def573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613e139190615dab565b9250925050915091565b5f61127a82614437565b613e2f614390565b7f7b765e0e932d348852a6f810bfa1ab891e259123f02db8cdcde614c570223357613e5981614264565b613e6161426e565b613e696144ff565b613e738383614af0565b6113086142c7565b5f73d999970138c2397ca8582710676a29da5b6da23d6385ef8b79613e9e6142a3565b6040516001600160e01b031960e084901b168152600481019190915260016024820152604401611356565b613f266040518061012001604052805f81526020015f81526020015f6001600160401b031681526020015f63ffffffff1681526020015f63ffffffff1681526020015f81526020015f81526020015f81526020015f151581525090565b61274273179e54e2096c93bb1c835a9797a5b70946086de963b0ffbb806040518163ffffffff1660e01b81526004015f60405180830381865af415801561244f573d5f5f3e3d5ffd5b613f7882611eb7565b613f8181614264565b611fbb8383614597565b5f613f94614390565b5f613f9e81614264565b7369e62255248a7240fc5189671d20edd1a069e10563976234cc613fc06142a3565b6040516001600160e01b031960e084901b16815260048101919091526024810187905260448101869052606401602060405180830381865af4158015614008573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061402c9190615b6b565b91505b5092915050565b5f5f5f5f5f6140436142a3565b60188101549550905084156140605761405b85614a9c565b614062565b5f5b60198201546016909201549596909591945061010090910460ff1692509050565b61408b6151c3565b612742738768f6f689d9ba1f0c08d418af8ff31ac820a4a563a3f8a30a6040518163ffffffff1660e01b81526004015f60405180830381865af415801561244f573d5f5f3e3d5ffd5b6140dc61426e565b6040516334e01c8f60e11b815260048101839052811515602482015273d72860da3bbbc064ba19ac5c8a9e49022b58cdb7906369c0391e90604401611212565b614124614c33565b565b5f61412f61426e565b738aeb59d677899431d029dbc6c8dfc8fad2aeb82163c5a359086119346142a3565b5f61415a6142d7565b603f015460ff16919050565b61416e61426e565b738768f6f689d9ba1f0c08d418af8ff31ac820a4a563f604c6df6040518163ffffffff1660e01b81526004015f6040518083038186803b1580156141b0575f5ffd5b505af41580156141c2573d5f5f3e3d5ffd5b505050506141246142c7565b6141d6614390565b5f6141e081614264565b7369e62255248a7240fc5189671d20edd1a069e1056387386d3c61168d6142a3565b6040805160a0810182525f80825260208201819052818301819052606082018190526080820152905163266e2b0360e11b8152600481018390526119049073d999970138c2397ca8582710676a29da5b6da23d90634cdc560690602401612435565b61257d8133614c96565b5f614277614ccf565b80549091506001190161429d57604051633ee5aeb560e01b815260040160405180910390fd5b60029055565b7fc49ad79e2b58679c441432bede06c67f7802343349e70ccf00d8d1ce92bb1b0090565b5f6142d0614ccf565b6001905550565b7f2420c1d967401a6739c551e175fd4dfa8e9cd5ee804155e89721bed004930b0090565b80546040516370a0823160e01b81525f9182916001600160a01b03909116906370a082319061432e9030906004016155b3565b602060405180830381865afa158015614349573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061436d9190615b6b565b905080836001015411614380575f61159c565b80836001015461159c9190615bd5565b614398614c33565b5f6143a16142d7565b601101546001600160a01b0316148015906143bf57506143bf614cf3565b1561412457604051639de6bad160e01b815260040160405180910390fd5b611fbb84856001600160a01b03166323b872dd86868660405160240161440593929190615b82565b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050614d07565b5f61127a64e8d4a5100083615e84565b6040516385ef8b7960e01b8152600481018290525f602482018190529073d999970138c2397ca8582710676a29da5b6da23d906385ef8b799060440161237a565b5f807ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0061127a565b614124614d6a565b6144c0614d6a565b614124614d8f565b5f6144d1614390565b61159c8383614d97565b7f02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b62680090565b614507612a1c565b156141245760405163d93c066560e01b815260040160405180910390fd5b5f61452e6142d7565b603181015490915060ff16614541575050565b6014810154614558906001600160a01b0316614e35565b5f82815260188201602052604090206005015460ff1615611246576040516328f7b79760e11b815260048101839052602401611877565b805160208201f35b5f6145a0614390565b61159c8383614e6f565b6145b2614ee5565b5f6145bb6147f3565b805460ff1916815590507f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516145f591906155b3565b60405180910390a150565b306001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016148061467057507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316614664614f0a565b6001600160a01b031614155b156141245760405163703e46dd60e11b815260040160405180910390fd5b7f189ab7a9244df0848122154315af71fe140f3db0fe014031783b0946b8c9d2e36146b881614264565b6146c0614390565b604051633e619e5f60e11b8152738768f6f689d9ba1f0c08d418af8ff31ac820a4a590637cc33cbe90611d3d9085906004016155b3565b816001600160a01b03166352d1902d6040518163ffffffff1660e01b8152600401602060405180830381865afa925050508015614751575060408051601f3d908101601f1916820190925261474e91810190615b6b565b60015b6147705781604051634c9c8ce360e01b815260040161187791906155b3565b5f516020615ed15f395f51905f5281146147a057604051632a87526960e21b815260048101829052602401611877565b6113088383614f1e565b306001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146141245760405163703e46dd60e11b815260040160405180910390fd5b7fcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f0330090565b61481f6142d7565b6031015460ff161561257d576040516328f7b79760e11b815260048101829052602401611877565b6148717fcb6c915afba301a06d8c17327f1f6eec8e262e5feb9a4db38c9ac4d14eb366a333613357565b61412457336040516350c7779760e11b815260040161187791906155b3565b6148986144ff565b5f6148a16147f3565b805460ff1916600117815590507f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586145e83390565b5f61127a64e8d4a5100083615e9b565b5f81601801545f1415806148fd5750600682015415155b8061490b5750601282015415155b806149195750600882015415155b8061492b5750614928826142fb565b15155b1561493857506001919050565b60058201546001600160a01b031680158061495e575060048301546001600160a01b0316155b1561496c5750600192915050565b5f5f826001600160a01b0316632f6b1f626040518163ffffffff1660e01b8152600401602060405180830381865afa9250505080156149c8575060408051601f3d908101601f191682019092526149c591810190615b6b565b60015b6149d757506001949350505050565b9150826001600160a01b0316630e9141926040518163ffffffff1660e01b8152600401602060405180830381865afa925050508015614a33575060408051601f3d908101601f19168201909252614a3091810190615b6b565b60015b614a4257506001949350505050565b9050109392505050565b60188201545f819003614a72576040516342e5afaf60e11b815260040160405180910390fd5b80821461127a57604051635c252f3b60e11b81526004810182905260248101839052604401611877565b5f811580614aae5750600160ff1b8210155b15614acf57604051635fea8ef360e01b815260048101839052602401611877565b614ada825f19615bd5565b9050600160ff1b81101561190457611904615e70565b6001600160a01b038216614b1757604051636cd2038560e11b815260040160405180910390fd5b306001600160a01b03831603614b4057604051637e69945160e11b815260040160405180910390fd5b805f03614b605760405163bc25207f60e01b815260040160405180910390fd5b5f614b696142a3565b9050614b7481614f73565b5f614b7e83614437565b90505f614b8e8360010154614437565b905080821115614bbb5760405163e2aaeb7b60e01b81526004810183905260248101829052604401611877565b83836001015f828254614bce9190615bd5565b90915550508254614be9906001600160a01b03168686615013565b846001600160a01b03167f0c9a0dce7b92cf97c29c155081f230310c7fd7ca4f3808bf70d8733f5168950d85604051614c2491815260200190565b60405180910390a25050505050565b5f614c3c6142d7565b6031810154909150610100900460ff1680614c625750602a810154600160e81b900460ff165b80614c7857506038810154600160901b900460ff165b1561257d57604051639de6bad160e01b815260040160405180910390fd5b614ca08282613357565b6112465760405163e2517d3f60e01b81526001600160a01b038216600482015260248101839052604401611877565b7f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f0090565b5f5f614cfd614ccf565b5460021492915050565b5f5f60205f8451602086015f885af180614d26576040513d5f823e3d81fd5b50505f513d91508115614d3d578060011415614d4a565b6001600160a01b0384163b155b15611fbb5783604051635274afe760e01b815260040161187791906155b3565b614d72615044565b61412457604051631afcd79f60e31b815260040160405180910390fd5b6142c7614d6a565b5f5f614da16144db565b9050614dad8484613357565b614e2c575f848152602082815260408083206001600160a01b03871684529091529020805460ff19166001179055614de23390565b6001600160a01b0316836001600160a01b0316857f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a4600191505061127a565b5f91505061127a565b336001600160a01b0382161461257d57604051633ee1754160e21b81526001600160a01b0382166004820152336024820152604401611877565b5f5f614e796144db565b9050614e858484613357565b15614e2c575f848152602082815260408083206001600160a01b0387168085529252808320805460ff1916905551339287917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a4600191505061127a565b614eed612a1c565b61412457604051638dfc202b60e01b815260040160405180910390fd5b5f5f516020615ed15f395f51905f52612589565b614f278261505d565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a2805115614f6b5761130882826150b7565b611246615129565b600181015481546040516370a0823160e01b81525f916001600160a01b0316906370a0823190614fa79030906004016155b3565b602060405180830381865afa158015614fc2573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614fe69190615b6b565b90508082111561130857604051637e81a69560e01b81526004810183905260248101829052604401611877565b6040516001600160a01b0383811660248301526044820183905261130891859182169063a9059cbb90606401614405565b5f61504d614488565b54600160401b900460ff16919050565b806001600160a01b03163b5f036150895780604051634c9c8ce360e01b815260040161187791906155b3565b5f516020615ed15f395f51905f5280546001600160a01b0319166001600160a01b0392909216919091179055565b60605f5f846001600160a01b0316846040516150d39190615eba565b5f60405180830381855af49150503d805f811461510b576040519150601f19603f3d011682016040523d82523d5f602084013e615110565b606091505b5091509150615120858383615148565b95945050505050565b34156141245760405163b398979f60e01b815260040160405180910390fd5b60608261515d576151588261519b565b61159c565b815115801561517457506001600160a01b0384163b155b156151945783604051639996b31560e01b815260040161187791906155b3565b508061159c565b8051156151aa57805160208201fd5b60405163d6bda27560e01b815260040160405180910390fd5b604051806101a001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020016152286040518060c001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f151581525090565b81525f6020820181905260408201819052606082018190526080820181905260a0820181905260c09091015290565b5f60e0828403128015615268575f5ffd5b509092915050565b5f60208284031215615280575f5ffd5b81356001600160e01b03198116811461159c575f5ffd5b5f5f602083850312156152a8575f5ffd5b82356001600160401b038111156152bd575f5ffd5b8301601f810185136152cd575f5ffd5b80356001600160401b038111156152e2575f5ffd5b8560208284010111156152f3575f5ffd5b6020919091019590945092505050565b6001600160a01b038116811461257d575f5ffd5b803561190481615303565b5f5f5f60608486031215615334575f5ffd5b833561533f81615303565b9250602084013561534f81615303565b929592945050506040919091013590565b5f5f5f5f5f60a08688031215615374575f5ffd5b853561537f81615303565b9450602086013561538f81615303565b9350604086013561539f81615303565b925060608601356153af81615303565b915060808601356153bf81615303565b809150509295509295909350565b5f5f604083850312156153de575f5ffd5b50508035926020909101359150565b5f602082840312156153fd575f5ffd5b5035919050565b5f60208284031215615414575f5ffd5b813561159c81615303565b5f5f60408385031215615430575f5ffd5b82359150602083013561544281615303565b809150509250929050565b5f5f5f5f60808587031215615460575f5ffd5b84359350602085013561547281615303565b93969395505050506040820135916060013590565b5f5f5f60608486031215615499575f5ffd5b83359250602084013561534f81615303565b801515811461257d575f5ffd5b5f602082840312156154c8575f5ffd5b813561159c816154ab565b5f610120820190508251825260208301516020830152604083015160408301526001600160401b0360608401511660608301526001600160401b03608084015116608083015260a083015161553360a08401826001600160401b03169052565b5060c083015161554760c084018215159052565b5060e083015161555b60e084018215159052565b5061010083015161402f61010084018215159052565b5f5f82840360c0811215615583575f5ffd5b8335925060a0601f1982011215615598575f5ffd5b506020830190509250929050565b6001600160a01b03169052565b6001600160a01b0391909116815260200190565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f191681016001600160401b0381118282101715615603576156036155c7565b604052919050565b5f6001600160401b03821115615623576156236155c7565b50601f01601f191660200190565b5f5f60408385031215615642575f5ffd5b823561564d81615303565b915060208301356001600160401b03811115615667575f5ffd5b8301601f81018513615677575f5ffd5b803561568a6156858261560b565b6155db565b81815286602083850101111561569e575f5ffd5b816020840160208301375f602083830101528093505050509250929050565b5f5f604083850312156156ce575f5ffd5b82356156d981615303565b946020939093013593505050565b5f5f5f606084860312156156f9575f5ffd5b505081359360208301359350604090920135919050565b60ff8116811461257d575f5ffd5b5f6020828403121561572e575f5ffd5b813561159c81615710565b5f5f82840360e081121561574b575f5ffd5b8335925060c0601f1982011215615598575f5ffd5b81516001600160a01b0390811682526020808401518216908301526040808401518216908301526060808401518216908301526080808401519091169082015260a08281015160e08301916157b7908401826155a6565b5060c083015161402f60c08401826155a6565b5f61012082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260018060a01b0360a08401511660a08301526001600160401b0360c08401511660c083015260e083015161555b60e084018215159052565b602081525f82518060208401528060208501604085015e5f604082850101526040601f19601f83011684010191505092915050565b5f5f6040838503121561587c575f5ffd5b82356156d981615710565b803561ffff81168114611904575f5ffd5b5f5f604083850312156158a9575f5ffd5b6158b283615887565b9150602083013561544281615303565b5f6101208201905082518252602083015160208301526001600160401b03604084015116604083015263ffffffff60608401511660608301526080830151615912608084018263ffffffff169052565b5060a083015160a083015260c083015160c083015260e083015160e083015261010083015161402f61010084018215159052565b5f61024082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c08301516159cd60c0840182805182526020810151602083015260408101516040830152606081015160608301526080810151608083015260a0810151151560a08301525050565b5060e08301516159e16101808401826155a6565b506101008301516159f66101a08401826155a6565b50610120830151615a0b6101c08401826155a6565b506101408301516001600160401b03166101e083015261016083015160ff1661020083015261018083015180151561022084015261402f565b5f5f60408385031215615a55575f5ffd5b823591506020830135615442816154ab565b82815261010081018235615a7a81615303565b6001600160a01b0316602083810191909152830135615a9881615303565b6001600160a01b0316604083810191909152830135615ab681615303565b6001600160a01b0316606083810191909152615ad3908401615317565b615ae060808401826155a6565b50615aed60808401615317565b615afa60a08401826155a6565b50615b0760a08401615317565b615b1460c08401826155a6565b50615b2160c08401615317565b615b2e60e08401826155a6565b509392505050565b83815260406020820152816040820152818360608301375f818301606090810191909152601f909201601f1916010192915050565b5f60208284031215615b7b575f5ffd5b5051919050565b6001600160a01b039384168152919092166020820152604081019190915260600190565b5f60208284031215615bb6575f5ffd5b815161159c816154ab565b634e487b7160e01b5f52601160045260245ffd5b8181038181111561127a5761127a615bc1565b8082018082111561127a5761127a615bc1565b5f60208284031215615c0b575f5ffd5b815161159c81615710565b5f5f60408385031215615c27575f5ffd5b82516020840151909250615442816154ab565b5f60208284031215615c4a575f5ffd5b815161159c81615303565b94855260208501939093526001600160a01b039190911660408401526060830152608082015260a00190565b5f60208284031215615c91575f5ffd5b81516001600160401b03811115615ca6575f5ffd5b8201601f81018413615cb6575f5ffd5b8051615cc46156858261560b565b818152856020838501011115615cd8575f5ffd5b8160208401602083015e5f91810160200191909152949350505050565b803563ffffffff81168114611904575f5ffd5b80356001600160401b0381168114611904575f5ffd5b8381526020810183905260e0810161ffff615d3884615887565b16604083015263ffffffff615d4f60208501615cf5565b1660608301526001600160401b03615d6960408501615d08565b1660808301526001600160401b03615d8360608501615d08565b1660a08301526001600160401b03615d9d60808501615d08565b1660c0830152949350505050565b5f5f60408385031215615dbc575f5ffd5b505080516020909101519092909150565b83815260208101839052610100810161ffff615de884615887565b16604083015261ffff615dfd60208501615887565b16606083015263ffffffff615e1460408501615cf5565b1660808301526001600160401b03615e2e60608501615d08565b1660a08301526001600160401b03615e4860808501615d08565b1660c08301526001600160401b03615e6260a08501615d08565b1660e0830152949350505050565b634e487b7160e01b5f52600160045260245ffd5b808202811582820484141761127a5761127a615bc1565b5f82615eb557634e487b7160e01b5f52601260045260245ffd5b500490565b5f82518060208501845e5f92019182525091905056fe360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc8f949a3ba351e10a4e8a55f43474eba190dceef5961d8b678c89e6dd8f5681ef55435dd261a4b9b3364963f7738a7a662ad9c84396d64be3365284bb7f0a5041a26469706673582212202429b976a2086b53bfda680ca991465ca6d02f6e1652cf2feb7fe7ea9c3a120564736f6c634300081e0033","name":"ReserveManager","is_blueprint":false,"license_type":"none","is_fully_verified":false,"is_verified_via_eth_bytecode_db":true,"language":"solidity","evm_version":"cancun","can_be_visualized_via_sol2uml":true,"is_verified_via_sourcify":true,"additional_sources":[{"file_path":"lib/openzeppelin-contracts/contracts/utils/Errors.sol","source_code":"// 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"},{"file_path":"lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol","source_code":"// 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"},{"file_path":"src/interfaces/IReserveLossGovernance.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\n/// @dev Minimal live timing surface used by ReserveManager's C-01 Guardian pre-arm.\ninterface IReserveLossGovernor {\n    function votingDelay() external view returns (uint256);\n    function votingPeriod() external view returns (uint256);\n    function timelock() external view returns (address);\n    function clock() external view returns (uint48);\n    function CLOCK_MODE() external view returns (string memory);\n}\n\ninterface IReserveLossTimelock {\n    function getMinDelay() external view returns (uint256);\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol","source_code":"// 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"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"../proxy/utils/Initializable.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 */\nabstract contract ReentrancyGuardUpgradeable is Initializable {\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    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard\n    struct ReentrancyGuardStorage {\n        uint256 _status;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ReentrancyGuard\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;\n\n    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {\n        assembly {\n            $.slot := ReentrancyGuardStorageLocation\n        }\n    }\n\n    /**\n     * @dev Unauthorized reentrant call.\n     */\n    error ReentrancyGuardReentrantCall();\n\n    function __ReentrancyGuard_init() internal onlyInitializing {\n        __ReentrancyGuard_init_unchained();\n    }\n\n    function __ReentrancyGuard_init_unchained() internal onlyInitializing {\n        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n        $._status = 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    function _nonReentrantBefore() private {\n        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n        // On the first call to nonReentrant, _status will be NOT_ENTERED\n        if ($._status == ENTERED) {\n            revert ReentrancyGuardReentrantCall();\n        }\n\n        // Any calls to nonReentrant after this point will fail\n        $._status = ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        $._status = 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        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n        return $._status == ENTERED;\n    }\n}\n"},{"file_path":"src/libraries/ReserveAccrualLifecycleLib.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {ReserveManager} from \"../ReserveManager.sol\";\n\nimport {ClaimBridge} from \"../ClaimBridge.sol\";\nimport {ICollateralRegistry} from \"../interfaces/ICollateralRegistry.sol\";\nimport {IAccrualLifecycle, IAccrualRegistry, IAccrualRisk} from \"../interfaces/IAccrualLifecycle.sol\";\nimport {AccrualBook} from \"./AccrualBook.sol\";\nimport {AccrualLoans} from \"./AccrualLoans.sol\";\nimport {AccrualCeiling} from \"./AccrualCeiling.sol\";\nimport {ReserveAccrualLib} from \"./ReserveAccrualLib.sol\";\nimport {ReserveRoundingLib} from \"./ReserveRoundingLib.sol\";\nimport {ReserveAccrualStorageLib} from \"./ReserveAccrualStorageLib.sol\";\nimport {ReserveStorageLib} from \"./ReserveStorageLib.sol\";\nimport {ReserveCreditLib} from \"./ReserveCreditLib.sol\";\n\n/// @title ReserveAccrualLifecycleLib\n/// @notice Receipt, amendment, default-stop and terminal accounting for continuously accrued loans.\n/// @dev Split from ReserveAccrualCreditLib so both deployable linked libraries retain material\n///      EIP-170 margin. Public methods execute by delegatecall in ReserveManager's context.\nlibrary ReserveAccrualLifecycleLib {\n    using AccrualBook for AccrualBook.Book;\n    using AccrualLoans for AccrualLoans.State;\n    using ReserveStorageLib for ReserveManager.ReserveStorage;\n\n    uint256 internal constant MAX_EXPOSURE = type(uint256).max / 10_000;\n\n    error AccrualCredit_WrongCaller(address expected, address caller);\n    error AccrualCredit_UnsupportedTerms(uint256 facilityId);\n    error AccrualCredit_Unknown(uint256 facilityId);\n    error AccrualCredit_ExposureCapacity();\n    error AccrualCredit_UnpostedRisk(uint256 facilityId);\n    error AccrualCredit_ReceiptMismatch(uint256 facilityId);\n    error AccrualCredit_InvalidWriteDown(uint256 facilityId);\n\n    event AccruedLoanPosted(uint256 indexed facilityId, address indexed asset, uint256 amount, uint256 faceAfter);\n    event AccrualLoanAligned(\n        uint256 indexed facilityId,\n        uint64 indexed closureNonce,\n        uint64 at,\n        uint256 positiveCorrection,\n        uint256 roundingLoss,\n        bool stopped\n    );\n    event AccrualPastDueSet(uint256 indexed facilityId, bool marked);\n    event AccrualCeilingReserved(uint256 indexed facilityId, uint256 previousCeiling, uint256 nextCeiling);\n\n    /// @notice Matches both signed receipt legs against debt, then measures the exact native cash arrival.\n    function repay(\n        ReserveManager.ReserveStorage storage native,\n        uint256 id,\n        address payer,\n        uint256 principal,\n        uint256 interest\n    ) public returns (uint256 outstanding) {\n        ReserveAccrualStorageLib.State storage s = _fresh();\n        _caller(s.modules.waterfall);\n        _identity(s, id);\n        ReserveRoundingLib.prepare(native, id);\n        s.busy = true;\n        AccrualLoans.LifecycleWork memory work =\n            s.loans.repay(id, principal, interest, ReserveAccrualStorageLib.now64());\n        _aligned(native, s, work);\n        uint256 total = principal + interest;\n        uint256 scale = s.loans.loans[id].terms.scale;\n        uint256 received = ReserveCreditLib.payAccrued(\n            native, id, payer, total / scale, work.principalReduction, work.interestReduction\n        );\n        if (received != total) revert AccrualCredit_ReceiptMismatch(id);\n        s.recordedFace -= total;\n        outstanding = native.deployed[id];\n        if (outstanding != s.loans.loans[id].principal + s.loans.loans[id].unpaidInterest) {\n            revert AccrualCredit_ReceiptMismatch(id);\n        }\n        // A maturity checkpoint stops the curve without marking the loan permanently stopped.\n        // Keep its ceiling on the remaining face so a later partial receipt cannot recreate\n        // reserved capacity for interest that the closed curve can never earn.\n        if (work.stopped || s.loans.loans[id].permanentlyStopped) _replaceCeiling(s, id, outstanding);\n        s.busy = false;\n    }\n\n    /// @notice Completes retirement only after the native face, bridge state and risk hooks have closed.\n    function retire(ReserveManager.ReserveStorage storage native, uint256 id) public {\n        ReserveAccrualStorageLib.State storage s = _fresh();\n        if (msg.sender != s.modules.waterfall && msg.sender != s.modules.defaultManager) {\n            revert AccrualCredit_WrongCaller(s.modules.waterfall, msg.sender);\n        }\n        _identity(s, id);\n        ClaimBridge.LoanState state = ClaimBridge(s.modules.bridge).facility(id).state;\n        if (\n            native.deployed[id] != 0\n                || (state != ClaimBridge.LoanState.Repaid && state != ClaimBridge.LoanState.Resolved)\n        ) {\n            revert AccrualCredit_ReceiptMismatch(id);\n        }\n        s.loans.retire(id, ReserveAccrualStorageLib.now64());\n        _replaceCeiling(s, id, 0);\n    }\n\n    /// @notice Synchronizes a native declared-loss face reduction without treating it as a receipt.\n    function writeDown(uint256 id, uint256 amount) public {\n        ReserveAccrualStorageLib.State storage s = _fresh();\n        _caller(s.modules.defaultManager);\n        _identity(s, id);\n        AccrualLoans.Loan storage loan = s.loans.loans[id];\n        uint256 face = loan.principal + loan.unpaidInterest;\n        if (!loan.permanentlyStopped || amount > face || ReserveAccrualStorageLib.facilityUnposted(id) != 0) {\n            revert AccrualCredit_InvalidWriteDown(id);\n        }\n        uint256 principal = amount < loan.principal ? amount : loan.principal;\n        loan.principal -= principal;\n        loan.unpaidInterest -= amount - principal;\n        // A mixed loss consumes uncapitalized PIK before cash interest. Preserve the subset\n        // identity even when the cascade reaches the interest layer.\n        if (loan.mixed && loan.unpaidCashInterest > loan.unpaidInterest) {\n            loan.unpaidCashInterest = loan.unpaidInterest;\n        }\n        s.recordedFace -= amount;\n        _replaceCeiling(s, id, face - amount);\n    }\n\n    /// @notice Replaces only future terms after the bridge consumes its exact signed amendment.\n    function amend(ReserveManager.ReserveStorage storage native, uint256 id, IAccrualLifecycle.Terms memory terms)\n        public\n    {\n        ReserveAccrualStorageLib.State storage s = _fresh();\n        _caller(s.modules.bridge);\n        _identity(s, id);\n        AccrualLoans.Loan storage loan = s.loans.loans[id];\n        if (terms.yearSeconds != 360 days && (loan.pik || terms.yearSeconds != 365 days)) {\n            revert AccrualCredit_UnsupportedTerms(id);\n        }\n        uint64 at = ReserveAccrualStorageLib.now64();\n        (uint256 principal, uint256 interest,) = s.loans.loanFace(id, at);\n        AccrualCeiling.Terms memory remaining;\n        remaining.face = principal + interest;\n        remaining.frozenBasis = !loan.pik\n            ? principal\n            : (loan.nextCapitalization != 0 && loan.nextCapitalization <= at ? remaining.face : loan.frozenPikBasis);\n        remaining.scale = loan.terms.scale;\n        remaining.yearSeconds = terms.yearSeconds;\n        remaining.rateBps = terms.rateBps;\n        remaining.at = at;\n        remaining.nextCapitalization = terms.nextPaymentDue;\n        remaining.paymentInterval = terms.paymentInterval;\n        remaining.maturity = terms.maturity;\n        uint256 ceiling = ReserveAccrualLib.loanCeiling(remaining, loan.pik);\n        _replaceCeiling(s, id, ceiling);\n        ReserveRoundingLib.prepare(native, id);\n        s.busy = true;\n        AccrualLoans.LifecycleWork memory work = s.loans.amend(\n            id,\n            AccrualLoans.Amendment({\n                balanceCeiling: ceiling,\n                yearSeconds: terms.yearSeconds,\n                rateBps: terms.rateBps,\n                nextPaymentDue: terms.nextPaymentDue,\n                paymentInterval: terms.paymentInterval,\n                maturity: terms.maturity\n            }),\n            at\n        );\n        _aligned(native, s, work);\n        s.busy = false;\n    }\n\n    /// @notice Replaces both future rates and the signed PIK schedule after exact bridge attestation.\n    function amendMixed(\n        ReserveManager.ReserveStorage storage native,\n        uint256 id,\n        IAccrualLifecycle.MixedTerms memory terms\n    ) public {\n        ReserveAccrualStorageLib.State storage s = _fresh();\n        _caller(s.modules.bridge);\n        _identity(s, id);\n        uint256 combinedRate = uint256(terms.cashRateBps) + terms.pikRateBps;\n        if (terms.yearSeconds != 360 days || terms.cashRateBps == 0 || terms.pikRateBps == 0 || combinedRate > 10_000) {\n            revert AccrualCredit_UnsupportedTerms(id);\n        }\n        AccrualLoans.Loan storage loan = s.loans.loans[id];\n        uint64 at = ReserveAccrualStorageLib.now64();\n        (uint256 principal, uint256 interest,) = s.loans.loanFace(id, at);\n        uint256 face = principal + interest;\n        // A principal receipt rebases only the cash curve. Until the next signed PIK\n        // capitalization the PIK curve can therefore retain a basis above current face.\n        // Replacing capacity from face alone would clip that already-signed coupon.\n        principal = face > loan.frozenPikBasis ? face : loan.frozenPikBasis;\n        uint256 ceiling = ReserveAccrualLib.loanCeiling(\n            AccrualCeiling.Terms({\n                face: face,\n                frozenBasis: principal,\n                scale: loan.terms.scale,\n                yearSeconds: terms.yearSeconds,\n                rateBps: uint16(combinedRate),\n                at: at,\n                nextCapitalization: terms.nextPikCapitalization,\n                paymentInterval: terms.pikCapitalizationInterval,\n                maturity: terms.maturity\n            }),\n            true\n        );\n        _replaceCeiling(s, id, ceiling);\n        ReserveRoundingLib.prepare(native, id);\n        s.busy = true;\n        AccrualLoans.LifecycleWork memory work = s.loans.amendMixed(\n            id,\n            AccrualLoans.MixedAmendment({\n                pikTerms: AccrualLoans.Amendment({\n                    balanceCeiling: ceiling,\n                    yearSeconds: terms.yearSeconds,\n                    rateBps: terms.pikRateBps,\n                    nextPaymentDue: terms.nextPikCapitalization,\n                    paymentInterval: terms.pikCapitalizationInterval,\n                    maturity: terms.maturity\n                }),\n                cashRateBps: terms.cashRateBps\n            }),\n            at\n        );\n        _aligned(native, s, work);\n        s.busy = false;\n    }\n\n    /// @notice Stops at declaration and posts the full earned claim before any default snapshot.\n    function stop(ReserveManager.ReserveStorage storage native, uint256 id) public {\n        ReserveAccrualStorageLib.State storage s = _fresh();\n        _caller(s.modules.defaultManager);\n        _identity(s, id);\n        ReserveRoundingLib.prepare(native, id);\n        s.busy = true;\n        AccrualLoans.LifecycleWork memory work = s.loans.stop(id, ReserveAccrualStorageLib.now64());\n        _aligned(native, s, work);\n        _replaceCeiling(s, id, native.deployed[id]);\n        s.busy = false;\n    }\n\n    /// @notice Sets a cohort only after posting its initial marked face, preventing double counting.\n    function setPastDue(uint256 id, bool marked) public {\n        ReserveAccrualStorageLib.State storage s = _fresh();\n        _caller(s.modules.defaultManager);\n        _identity(s, id);\n        if (marked && ReserveAccrualStorageLib.facilityUnposted(id) != 0) revert AccrualCredit_UnpostedRisk(id);\n        s.loans.book.setPastDue(id, marked, ReserveAccrualStorageLib.now64());\n        emit AccrualPastDueSet(id, marked);\n    }\n\n    function _aligned(\n        ReserveManager.ReserveStorage storage native,\n        ReserveAccrualStorageLib.State storage s,\n        AccrualLoans.LifecycleWork memory work\n    ) private {\n        _post(native, s, work.facilityId, work.posting);\n        if (work.roundingLoss != 0) ReserveRoundingLib.allocate(native, work);\n        emit AccrualLoanAligned(\n            work.facilityId, work.closureNonce, work.at, work.positiveCorrection, work.roundingLoss, work.stopped\n        );\n    }\n\n    function _post(\n        ReserveManager.ReserveStorage storage native,\n        ReserveAccrualStorageLib.State storage s,\n        uint256 id,\n        uint256 amount\n    ) private {\n        if (amount == 0) return;\n        ReserveAccrualStorageLib.Identity storage identity = s.identities[id];\n        native.deployed[id] += amount;\n        native.totalDeployedPrincipal += amount;\n        s.recordedFace += amount;\n        IAccrualRegistry(s.modules.registry).recordAccruedExposure(\n            identity.classId, identity.borrowerId, identity.stateId, amount\n        );\n        if (s.loans.book.entries[id].pastDue) IAccrualRisk(s.modules.defaultManager).onAccrualPosted(id, amount);\n        emit AccruedLoanPosted(id, identity.asset, amount, native.deployed[id]);\n    }\n\n    function _admitAdditional(ReserveAccrualStorageLib.State storage s, uint256 additional) private view {\n        uint256 effective = ICollateralRegistry(s.modules.registry).totalBookExposure();\n        uint256 future = _reservedExposure(s);\n        if (\n            effective > MAX_EXPOSURE || future > MAX_EXPOSURE - effective\n                || additional > MAX_EXPOSURE - effective - future\n        ) revert AccrualCredit_ExposureCapacity();\n    }\n\n    function _reservedExposure(ReserveAccrualStorageLib.State storage s) private view returns (uint256 amount) {\n        uint256 effectiveFace = s.recordedFace + ReserveAccrualStorageLib.unposted();\n        return s.reservedCeilings > effectiveFace ? s.reservedCeilings - effectiveFace : 0;\n    }\n\n    function _replaceCeiling(ReserveAccrualStorageLib.State storage s, uint256 id, uint256 next) private {\n        uint256 previous = s.identities[id].reservedCeiling;\n        if (next > previous) _admitAdditional(s, next - previous);\n        s.reservedCeilings = s.reservedCeilings - previous + next;\n        s.identities[id].reservedCeiling = next;\n        emit AccrualCeilingReserved(id, previous, next);\n    }\n\n    function _fresh() private view returns (ReserveAccrualStorageLib.State storage s) {\n        ReserveAccrualLib.requireFresh();\n        s = ReserveAccrualStorageLib.state();\n        if (!s.enabled) revert ReserveAccrualLib.ReserveAccrual_NotEnabled();\n    }\n\n    function _identity(ReserveAccrualStorageLib.State storage s, uint256 id) private view {\n        if (!s.identities[id].known) revert AccrualCredit_Unknown(id);\n    }\n\n    function _caller(address expected) private view {\n        if (msg.sender != expected) revert AccrualCredit_WrongCaller(expected, msg.sender);\n    }\n}\n"},{"file_path":"src/libraries/Config.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\n/// @title Config\n/// @notice Single source of truth for token naming and protocol default parameters\n///         (brief Part 12: names are final but kept in one module so a rebrand is a\n///         single change).\nlibrary Config {\n    // ── Token naming (final per brief Part 12) ──────────────────────────\n    string internal constant USDFR_NAME = \"Forest Road Dollar\";\n    string internal constant USDFR_SYMBOL = \"USDfr\";\n    string internal constant SUSDFR_NAME = \"Staked Forest Road Dollar\";\n    string internal constant SUSDFR_SYMBOL = \"sUSDfr\";\n    string internal constant GROVE_NAME = \"Forest Road Grove\";\n    string internal constant GROVE_SYMBOL = \"GROVE\";\n    string internal constant SGROVE_NAME = \"Staked Forest Road Grove\";\n    string internal constant SGROVE_SYMBOL = \"sGROVE\";\n\n    // ── Collateral class IDs (ADR-0003 as amended: all FIVE live at genesis) ──\n    uint256 internal constant CLASS_FILM_TAX_CREDITS = 1;\n    uint256 internal constant CLASS_RENEWABLE_ENERGY = 2;\n    uint256 internal constant CLASS_LIFE_SCIENCES = 3;\n    uint256 internal constant CLASS_REAL_ESTATE = 4;\n    /// @dev Marked-to-market, related-party class (ADR-0015) — distinct margin/\n    ///      liquidation model, NOT the receivable model of classes 1-4.\n    uint256 internal constant CLASS_DIGITAL_ASSETS = 5;\n    uint256 internal constant NUM_CLASSES = 5;\n\n    // ── Credit-layer defaults (ADR-0004 / ADR-0014; governance-adjustable) ──\n    /// @dev USD amounts in 18 decimals (USDfr units).\n    uint256 internal constant DEFAULT_FIRST_LOSS_PER_CLASS = 10_000_000e18;\n    uint256 internal constant SGROVE_UNBONDING_PERIOD = 21 days;\n    // Reward streaming window (ADR-0021 / audit R4-EC1): notified rewards drip linearly\n    // over this period rather than distributing instantly, so rewards accrue in real time\n    // (Pendle-compatible) and cannot be sandwiched by a deposit-before-harvest. Governance\n    // tunable via setRewardsDuration, bounded by SGROVE_MAX_REWARDS_DURATION.\n    uint64 internal constant SGROVE_REWARDS_DURATION = 7 days;\n    uint64 internal constant SGROVE_MAX_REWARDS_DURATION = 365 days;\n\n    // ── Governance defaults (ADR-0013/0021; FR-controlled at launch) ─────\n    /// @dev Fixed at genesis, minted to the Forest Road treasury (ADR-0013).\n    uint256 internal constant GROVE_INITIAL_SUPPLY = 1_000_000_000e18;\n    uint48 internal constant GOV_VOTING_DELAY = 1 days;\n    /// @dev Fresh Ethereum genesis: owner-approved 2026-09-18; existing proxy settings persist.\n    uint32 internal constant GOV_VOTING_PERIOD = 2 days;\n    uint256 internal constant GOV_PROPOSAL_THRESHOLD = 1_000_000e18; // 0.1% of supply\n    uint256 internal constant GOV_QUORUM_FRACTION = 4; // % of total votes\n    uint256 internal constant TIMELOCK_MIN_DELAY = 2 days;\n    /// @dev C-01 reserve-loss pre-arm floor. The live arm duration is derived from the\n    ///      bound Governor and Timelock at arm time and may be longer; this immutable\n    ///      floor prevents a broken or shortened timing dependency from failing open.\n    uint256 internal constant RESERVE_LOSS_MIN_PREARM_DURATION = 11 days;\n    uint256 internal constant RESERVE_LOSS_SCHEDULING_SLACK = 1 days;\n    /// @dev Preserve the original curator pre-arm floor when launch voting is shortened.\n    ///      Longer live governance schedules still extend the derived protection.\n    uint256 internal constant CURATOR_PRE_ARM_MIN_GOVERNANCE_PATH = 10 days;\n\n    /// @dev Protocol fee on distributed interest (waterfall), in bps. Launch default\n    ///      is deliberately modest; governance-adjustable; economic-review item.\n    uint256 internal constant DEFAULT_PROTOCOL_FEE_BPS = 1_000; // 10% of interest\n\n    /// @dev AUDIT FIX (SWEEP-2 S2-F1) — PERMANENT HARD CAP ON THE INTEREST PROTOCOL FEE.\n    ///      DO NOT DELETE AND DO NOT RAISE WITHOUT FOREST ROAD DIRECTION.\n    ///\n    ///      Before this, `WaterfallEngine.setProtocolFee` was bounded only by `Config.BPS` — it was\n    ///      the ONLY fee rate in the protocol with no permanent ceiling, while its three siblings\n    ///      (`setOriginationFee` -> `MAX_ORIGINATION_FEE_BPS`, `sUSDfr.setPerformanceFee` ->\n    ///      `MAX_PERFORMANCE_FEE_BPS`, `setManagementFee` -> `MAX_MANAGEMENT_FEE_BPS`) all carry\n    ///      one and two of those are PUBLISHED to holders (`maxPerformanceFeeBps()`,\n    ///      `maxManagementFeeBps()`) and described here as \"permanent in v1\". MEASURED: 10,000 bps\n    ///      was accepted and took the ENTIRE senior yield leg (`toVault` 0, `toFee` the whole\n    ///      interest receipt). Because `_routeInterest` takes this fee FIRST, off the same senior\n    ///      income stream the vault's 20% performance cap protects, total capture of senior yield\n    ///      was reachable AROUND a cap the protocol advertises as permanent — and the fee recipient\n    ///      holds plain USDfr, so it is not a cascade layer.\n    ///\n    ///      The LEVEL mirrors `MAX_PERFORMANCE_FEE_BPS` (20%), i.e. 2x the launch default, which\n    ///      is the house convention for \"a permanent ceiling with real governance room under it\".\n    ///      The level is an economic-review item; the EXISTENCE of the ceiling is not.\n    uint16 internal constant MAX_PROTOCOL_FEE_BPS = 2_000; // 20% of interest — permanent in v1\n\n    /// @dev Protocol-level performance fee on sUSDfr NAV gains above the global,\n    ///      post-fee high-water mark. Launches at 10% and may only be changed\n    ///      prospectively by timelocked governance. The hard cap is permanent in v1.\n    uint16 internal constant DEFAULT_PERFORMANCE_FEE_BPS = 1_000; // 10% of profit\n    uint16 internal constant MAX_PERFORMANCE_FEE_BPS = 2_000; // 20% of profit\n\n    /// @dev Effective-annual sUSDfr management fee on a 365-day basis. Launches disabled\n    ///      and may only be enabled prospectively by timelocked governance. Fractional\n    ///      periods use geometric retention; the hard cap is permanent in v1.\n    uint16 internal constant DEFAULT_MANAGEMENT_FEE_BPS = 0;\n    uint16 internal constant MAX_MANAGEMENT_FEE_BPS = 200; // 2% per 365-day year\n    uint64 internal constant MANAGEMENT_FEE_YEAR = 365 days;\n\n    /// @dev Origination fee charged at facility funding, in bps of principal (OID\n    ///      mechanics: the borrower nets principal minus fee). Market range for the\n    ///      book's verticals is ~1-2% (ADR-0019); per-class governance-adjustable,\n    ///      capped at MAX_ORIGINATION_FEE_BPS; economic-review item.\n    uint16 internal constant DEFAULT_ORIGINATION_FEE_BPS = 200; // 2% of principal (Forest Road direction)\n    uint16 internal constant MAX_ORIGINATION_FEE_BPS = 1_000; // 10% hard cap\n\n    /// @dev Margin-call cure window for marked-to-market classes (ADR-0015:\n    ///      \"hours-to-days\"). Governance-adjustable per class; economic-review item.\n    uint64 internal constant DEFAULT_MARGIN_CURE_WINDOW = 1 days;\n\n    // ── Liquidity-layer defaults (ADR-0010/0022; governance-adjustable) ──\n    /// @dev Settlement HEARTBEAT (ADR-0022): how often `closeEpoch` may run and refresh\n    ///      the liquidity budget. Under the ADR-0022 cooldown model this is NOT the\n    ///      holding period — `DEFAULT_REDEEM_COOLDOWN` is. The heartbeat must be SHORT\n    ///      relative to the cooldown so the effective wait ≈ cooldown (no compounding).\n    ///      Heartbeat/liquidity calibration is an economic-review item (ADR-0022 §X.5).\n    uint64 internal constant DEFAULT_EPOCH_DURATION = 1 days;\n    /// @dev Share of the treasury's idle canonical-USDC liquidity a settlement may\n    ///      distribute to the queue PER\n    ///      HEARTBEAT, leaving the remainder for direct USDfr redemptions. Rescaled from\n    ///      the legacy 50%/30-day batch to preserve ~50%/30-day throughput at a 1-day\n    ///      heartbeat (5000/30 ≈ 167). Economic-review item (ADR-0022 §X.5).\n    uint16 internal constant DEFAULT_EPOCH_LIQUIDITY_BPS = 167; // ~1.67%/day ≈ 50%/30d\n\n    /// @dev ADR-0022: forced per-request redemption cooldown. A queued redemption cannot\n    ///      settle until `requestedAt + DEFAULT_REDEEM_COOLDOWN`. Matches\n    ///      `SGROVE_UNBONDING_PERIOD` (21 days) — long enough that a senior cannot exit\n    ///      ahead of a foreseeable loss (front-running / loss-dodge defense).\n    uint64 internal constant DEFAULT_REDEEM_COOLDOWN = 21 days;\n\n    /// @dev AUDIT FIX (SWEEP-2 CSG-F2) — the UPPER bound on `RedemptionQueue.setRedeemCooldown`.\n    ///      The LOWER bound is `DEFAULT_REDEEM_COOLDOWN` itself and is not a separate constant on\n    ///      purpose: the G2W relief ramp in `CollateralRegistry.conservativeSeniorMark` is written\n    ///      against that exact constant, so the floor must BE it — a second constant is a second\n    ///      thing to forget to move (SEAM-1). 180 days is the same order as\n    ///      `SGrove.setUnbondingPeriod`'s `AUDIT FIX (L)` ceiling and exists for the same reason:\n    ///      an unbounded setter can permanently freeze every queued senior exit by fat finger.\n    uint64 internal constant MAX_REDEEM_COOLDOWN = 180 days;\n\n    /// @dev C-1 anti-dust-wedge floor. Minimum REALIZED value (in USDfr, 18 decimals) a\n    ///      redemption request must be worth to enter the queue — $1. `closeEpoch` never burns a\n    ///      position worth zero at the conservative mark; it stops there, so a sub-wei \"dust\" head\n    ///      could otherwise wedge the queue for the real positions behind it. Barring dust at entry\n    ///      makes that wedge reachable only when the exchange rate has collapsed by >1e18x (a\n    ///      >99.9999999999999999% senior loss), at which point every realistically-sized position\n    ///      is ALSO worth under a wei and halting the queue is the correct behaviour, not griefing.\n    ///      Measured at the REALIZED rate (`convertToAssets`), not the conservative one, so a\n    ///      declared-but-unrealized impairment does not lock new exits out of the queue.\n    ///      Governance-tunable via `RedemptionQueue.setMinRedemptionValue`.\n    uint256 internal constant DEFAULT_MIN_REDEMPTION_VALUE = 1e18; // 1 USDfr ($1)\n\n    // ── Optional senior-yield vesting (ADR-0023; governance-adjustable) ──\n    /// @dev Realized senior yield may be vested linearly into `sUSDfr.totalAssets()`\n    ///      instead of landing as an instant step. Only ALREADY-REALIZED yield can be\n    ///      streamed — nothing forward-looking is ever pre-credited, so ADR-0002\n    ///      variable-yield pass-through is untouched. Pendle accepts a valid stepwise SY\n    ///      exchange rate; smoothing is an optional market-design control against\n    ///      payment-timing games and abrupt asset-denominated price moves, not a Pendle\n    ///      protocol prerequisite. Forest Road selected instant recognition for launch.\n    ///      Governance may enable a non-zero window prospectively after economic review.\n    uint64 internal constant DEFAULT_YIELD_VESTING_PERIOD = 0;\n    /// @dev Hard ceiling on a newly opened stream. The vault also stores an absolute stream\n    ///      deadline that non-zero governance re-tunes and rollovers may shorten but never\n    ///      extend, so alternating settings cannot defer the same realized yield indefinitely.\n    uint64 internal constant MAX_YIELD_VESTING_PERIOD = 30 days;\n\n    /// @notice RAMP POSTURE (Forest Road direction, 2026-07-21): concentration limits are\n    ///         seeded WIDE OPEN so idle deposit capital can be deployed into originations —\n    ///         initially a facility to the digital-assets book — without a concentration\n    ///         dimension blocking it before the book has any diversity to measure.\n    /// @dev At `BPS` (100%) the admission test `exp > limitBps * base / BPS` reduces to\n    ///      `exp > base`, and no single dimension can exceed the book, so NOTHING BINDS.\n    ///      Two consequences the operator must hold in mind, both stated rather than implied:\n    ///        1. Concentration TELEMETRY GOES DARK. `isOverConcentrated`, the drift events and\n    ///           `concentrationHeadroom` all measure against the configured limit, so at 100%\n    ///           they report \"clean\" unconditionally. There is no on-chain early warning while\n    ///           this posture holds; monitoring must come from the `ExposureRecorded` stream.\n    ///        2. RATCHETING DOWN LATER IS A CLIFF. Limits are ADMISSION control and a standing\n    ///           breach is permitted (a decrease can never be blocked, or a risk limit could\n    ///           veto a loss being realized). So whatever is concentrated when a real limit is\n    ///           set will instantly read as breached and be frozen from further growth until\n    ///           the book grows around it. Set the first real limits AT or slightly above the\n    ///           actual composition at that time, then step down — do not jump straight to the\n    ///           target.\n    ///      `Validate.s.sol` prints an unmissable posture block whenever this is in force, so\n    ///      an unlimited deployment can never produce output identical to a limited one.\n    uint16 internal constant RAMP_CONCENTRATION_LIMIT_BPS = 10_000; // 100% = unbounded\n\n    uint256 internal constant BPS = 10_000;\n\n    /// @notice Forward weight, in bps, that an UNATTESTED permissionless past-due mark\n    ///         (`DefaultManager.markPastDue`) carries in the conservative redemption NAV,\n    ///         relative to an ATTESTED declared default. Used as the fallback whenever\n    ///         `DefaultManager`'s governed slot reads zero (see `pastDueWeightBps()`).\n    /// @dev OWNER DECISION (Forest Road, 2026-08-07): \"An unattested, permissionless past-due\n    ///      mark should NOT carry the same forward weight as an attested declared default.\"\n    ///\n    ///      DERIVED, NOT INVENTED. The protocol already governs an evidence ladder — but only on\n    ///      the marked-to-market side, where the three rungs are per-class registry parameters:\n    ///        - `maxLtvBps`         the rung the protocol is willing to be exposed at (healthy);\n    ///        - `marginCallLtvBps`  the rung at which a PERMISSIONLESS, REVERSIBLE early warning\n    ///                              fires (`marginCall`) — forward impairment weight ZERO, it only\n    ///                              starts a cure clock;\n    ///        - `liquidationLtvBps` the terminal rung, where `liquidate` records the FULL\n    ///                              outstanding into the impairment pool and `realizeLoss` becomes\n    ///                              reachable — forward impairment weight ONE.\n    ///      `markPastDue` is the receivable-side analogue of the MARGIN-CALL rung: permissionless,\n    ///      reversible, early, and strictly BEFORE the terminal attested rung (`declareDefault`).\n    ///      Governance placed that early rung exactly half way along the governed deterioration\n    ///      band. From the mainnet-v1 class-5 tuple in `script/Deploy.s.sol`\n    ///      (maxLtv 5_000, marginCall 6_500, liquidation 8_000):\n    ///\n    ///          (marginCallLtvBps - maxLtvBps) / (liquidationLtvBps - maxLtvBps)\n    ///            = (6_500 - 5_000) / (8_000 - 5_000) = 1_500 / 3_000 = 1/2 = 5_000 bps.\n    ///\n    ///      WHY NOT THE ADVANCE RATE ALONE. `maxLtvBps`/`ltvBps` cannot supply this weight, and the\n    ///      reasoning is recorded here so it is not re-attempted: the advance rate is DEFINED as the\n    ///      break-even recovery on the attested claim face (ClaimBridge documents the denominator as\n    ///      `principal * BPS / ltvBps`). Senior loss is `max(0, principal - recovery)`, so at a\n    ///      recovery equal to the advance rate the loss is identically ZERO — the advance rate\n    ///      derives a weight of 0, which re-opens H-5 and D5-03. Worse, every variant that forces a\n    ///      positive number out of it (haircut on face, re-advance against carried principal) is\n    ///      MONOTONE THE WRONG WAY: it marks a more conservatively underwritten facility harder.\n    ///\n    ///      DO NOT set this to zero (re-opens H-5: a conflicted servicer can sit on a declaration\n    ///      while seniors exit at par) or to `BPS` (restores the defect this constant fixes).\n    ///      `CollateralRegistry.setPastDueWeight` enforces both bounds.\n    uint256 internal constant DEFAULT_PAST_DUE_WEIGHT_BPS = 5_000; // 50%\n\n    /// @notice sUSDfr entry guard (audit H-3 residual): the maximum ratio of the STRANDED,\n    ///         realized-but-unvested yield stream (`sUSDfr.unvestedYield()`) to the DEPOSIT BASE\n    ///         (`sUSDfr.totalAssets()`) that vault entry tolerates before `deposit`/`mint` close as\n    ///         degenerate.\n    /// @dev THE HAZARD (ADR-0023): the vault physically holds realized yield that vests linearly\n    ///      into `totalAssets()` over a window and is EXCLUDED from `totalAssets()` until it does.\n    ///      Deposits price on `totalAssets()` (OZ's un-overridden `_convertToShares`), so a\n    ///      depositor entering while that stranded stream is large relative to the base buys shares\n    ///      cheaply and then skims a pro-rata slice of the stream as it vests — extracting from the\n    ///      incumbents who funded it. The hazard scales with `unvestedYield() / totalAssets()`, so\n    ///      the guard keys on exactly that ratio.\n    ///\n    ///      CALIBRATION (economic-review item; audit finding #3 re-key from 10 to 3, then audit\n    ///      R16-01). `sUSDfr._capStreamToBase` enforces a retention boundary against the ACTUAL\n    ///      staked base on both sides of the vault: after every yield delivery AND before every\n    ///      queue outflow, at most `1/(K+1)` of physical vault USDfr remains unvested and any\n    ///      excess is recognized immediately. A healthy low-staking vault therefore cannot be\n    ///      closed by receiving a payment that is large relative to deposits (FRV-FS-03), nor by\n    ///      an ordinary settlement shrinking the base under a live stream (RC-03).\n    ///      The guard remains meaningful after a senior write-down, which burns the recognized\n    ///      base while leaving an already-live stream physically present.\n    ///\n    ///      WHY 3 AND NOT 10 (the audit residual). The OLD `K = 10` reopened entry the moment the\n    ///      ratio fell to 10 — with the stranded stream still 10/11 (~91%) of the vault balance —\n    ///      leaving a near-total skim band `(0, 10]` open. It did NOT \"close the entire band\": near\n    ///      the top of that band a fresh depositor could still skim ~91% of the vault as the stream\n    ///      vested. Dropping to `K = 3` collapses the open band to `(0, 3)`. `K = 3` bounds the\n    ///      excluded stream at the closure point to 3/4 (~75%) of physical vault assets. It is a\n    ///      DIMENSIONLESS ratio, not a wei level, so it holds identically at every vault scale.\n    ///\n    ///      CORRECTION (AUDIT R16-01, HIGH — the previous justification of the open band was\n    ///      FALSE; do not restore it). This comment used to argue that the top of the `(0, K]` band\n    ///      is \"only reachable while the withheld stream is a MAJORITY of the vault, an\n    ///      already-catastrophic near-total-write-down state, never a healthy one\". That was wrong,\n    ///      and `K` was never what bounded a routine deposit's skim. The FRV-FS-03 inflow leg\n    ///      created exactly that ratio in a HEALTHY vault: the cap retained `K/(K+1)` of the\n    ///      balance, the largest retention the guard tolerates, which parks the vault at precisely\n    ///      `unvestedYield() == K * totalAssets()` — and `_isDegenerate`'s strict `>` left entry\n    ///      OPEN on that point. Servicing payments are sized off book principal, not off live\n    ///      sUSDfr supply, so any payment large relative to the staked base reached it. What bounds\n    ///      the routine skim is the CAP's retention target, now `1/(K+1)`: healthy operation parks\n    ///      at ratio `1/K`, a factor of `K^2` inside this guard, with a minority (25%) of the\n    ///      vault's cash excluded, and the boundary itself is now CLOSED (`>=`). The band between\n    ///      `1/K` and `K` is reachable only through a realized loss or a governance re-pricing of\n    ///      the vesting window.\n    ///\n    ///      Kept a constant rather than a governance-tunable for\n    ///      this pass: like `SUSDFR_MAX_SHARE_PRICE_COLLAPSE`, it is a defensive safety floor, not an\n    ///      operating knob, and adding storage/setter surface to the namespaced vault struct for it\n    ///      is unwarranted complexity here; a future pass may promote it to a governed parameter.\n    ///      See `SUSDfr._isDegenerate` and `SUSDfr._capStreamToBase`.\n    uint256 internal constant SUSDFR_MAX_STRANDED_YIELD_RATIO = 3;\n\n    /// @dev AUDIT R15-01. Vault entry closes once the realized per-share rate has collapsed to\n    ///      below `1 / SUSDFR_DEGENERATE_RATE_DIVISOR` of the stored high-water mark.\n    ///\n    ///      WHY A SECOND BAND IS NEEDED. `SUSDFR_MAX_STRANDED_YIELD_RATIO` above keys on\n    ///      `unvestedYield()`, which is identically zero at the launch instant-recognition policy\n    ///      (`DEFAULT_YIELD_VESTING_PERIOD == 0`). That band therefore cannot fire at launch,\n    ///      leaving only the `totalAssets() == 0` POINT — and one wei of a permissionless USDfr\n    ///      transfer steps off a point. `_isDegenerate`'s own rationale states the hazard is the\n    ///      whole neighbourhood, not the point; this restores the neighbourhood at every vesting\n    ///      setting.\n    ///\n    ///      WHY PAR IS THE REFERENCE. The stored high-water mark was tried first and rejected:\n    ///      `_accrueFees`'s empty-supply branch ratchets it to `(assets + 1) * 1e18` whenever any\n    ///      balance exists while `totalSupply() == 0`, so a pre-seed donation could inflate the\n    ///      hurdle arbitrarily and then permanently close entry through this band. That is\n    ///      harmless while the HWM only suppresses fees, and becomes a brick the moment entry\n    ///      depends on it — the invariant suite caught exactly that. Par is derived from the\n    ///      token's own decimals, is scale-free, and no actor can move it.\n    ///\n    ///      WHY 100. The band must separate a catastrophic collapse from a merely bad year, because\n    ///      closing entry is a governance event: a vault below 1% of its high-water mark is the\n    ///      near-total write-down the guard exists for, while a 50%-drawdown vault stays open to\n    ///      new capital. ECONOMIC-REVIEW ITEM, on the same footing as `K = 3` above — the shape is\n    ///      a safety floor, but the exact multiple is a judgement about when recapitalization must\n    ///      route through governance rather than through an ordinary deposit.\n    uint256 internal constant SUSDFR_DEGENERATE_RATE_DIVISOR = 100;\n}\n"},{"file_path":"src/libraries/ReserveStorageLib.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {IReserveManager} from \"../interfaces/IReserveManager.sol\";\nimport {ReserveManager} from \"../ReserveManager.sol\";\nimport {ReserveAccrualStorageLib} from \"./ReserveAccrualStorageLib.sol\";\n\n/// @title ReserveStorageLib — the ReserveManager's namespaced storage and its shared primitives\n///\n/// @notice EXTRACTED 2026-09-09 FOR EIP-170. `ReserveManager` shipped with 9 bytes of margin and\n///         went 184 bytes over the moment PIK capitalisation was added, which froze the live\n///         mainnet implementation against any new function at all. Forest Road directed the same\n///         library extraction BSC used (decision 10). This library holds the pieces the extracted\n///         bodies need in common.\n///\n/// @dev THE STORAGE STRUCT IS NOT HERE, AND THAT IS DELIBERATE. An earlier draft of this file did\n///      hold `ReserveStorage`, and this comment described that. It was wrong to keep either. The\n///      struct, its ERC-7201 storage-location annotation and the single `$.slot` assignment all\n///      stay in `ReserveManager.sol`; this library takes `ReserveManager.ReserveStorage storage`\n///      and is HANDED the pointer.\n///\n///      The reason is the gates. Moving the struct into a library is layout-identical, but\n///      `check-storage-layout` keys on the DECLARING FILE and reads the move as a struct REMOVAL,\n///      which it will only baseline under `--allow-removals`, a flag whose own message means \"this\n///      proxy is being freshly redeployed\". ReserveManager is a live mainnet proxy and is not. It\n///      also requires exactly one `$.slot` assignment in the declaring file, so moving the struct\n///      without moving that assignment fails outright. Leaving the declaration where it is makes\n///      the extraction layout-neutral BY CONSTRUCTION: both storage baselines were untouched by the\n///      commit that introduced this library, which is the strongest evidence available that nothing\n///      moved. DO NOT \"tidy\" the struct into this file.\n///\n/// @dev EVERY FUNCTION HERE IS `internal`, DELIBERATELY. An `internal` library function is inlined\n///      into its caller and saves no bytecode; the size relief comes from `ReserveCreditLib`, whose\n///      functions are `public` and therefore deployed separately and reached by delegatecall. These\n///      must stay `internal` for a second reason: a library calling ANOTHER library's `public`\n///      function leaves a placeholder that halmos cannot link, and every symbolic proof then fails\n///      while `forge test` and the size gate stay green.\nlibrary ReserveStorageLib {\n    /// @dev 1e18 value units per 1e6 USDC unit.\n    uint256 internal constant USDC_SCALE = 1e12;\n\n    /// @notice Storage-only native backing, including earned unposted receivables before marks.\n    function backingValue(ReserveManager.ReserveStorage storage native) internal view returns (uint256) {\n        return normalize(native.idleUSDCUnits) + native.totalDeployedPrincipal + ReserveAccrualStorageLib.unposted()\n            - native.totalPrincipalImpairment;\n    }\n\n    function normalize(uint256 amount) internal pure returns (uint256) {\n        return amount * USDC_SCALE;\n    }\n\n    function denormalize(uint256 value) internal pure returns (uint256) {\n        return value / USDC_SCALE;\n    }\n\n    /// @dev Shared fail-closed predicate for every USDC out-door. Restoring custody or completing\n    ///      the arm-bound write-down clears the objective condition without a separate latch.\n    function requireIdleFullyCustodied(ReserveManager.ReserveStorage storage $) internal view {\n        uint256 recorded = $.idleUSDCUnits;\n        uint256 live = $.usdcToken.balanceOf(address(this));\n        if (recorded > live) revert IReserveManager.ReserveManager_IdleCustodyShortfall(recorded, live);\n    }\n\n    /// @dev A write-down is the realization of loss, so the mark already carried against that loss\n    ///      must be consumed to avoid counting the same dollar twice.\n    function realizeImpairmentOnWriteDown(\n        ReserveManager.ReserveStorage storage $,\n        uint256 facilityId,\n        uint256 writeDown\n    ) internal {\n        uint256 recognized = $.principalImpairment[facilityId];\n        if (recognized == 0) return;\n        uint256 consumed = writeDown < recognized ? writeDown : recognized;\n        consumeImpairment($, facilityId, recognized, consumed);\n    }\n\n    /// @dev Cash repayment is not evidence that a particular impairment recovered. It may only\n    ///      release the portion that would otherwise exceed the facility's remaining face.\n    function clampImpairmentToRemainingFace(\n        ReserveManager.ReserveStorage storage $,\n        uint256 facilityId,\n        uint256 remainingFace\n    ) internal {\n        uint256 recognized = $.principalImpairment[facilityId];\n        if (recognized <= remainingFace) return;\n        consumeImpairment($, facilityId, recognized, recognized - remainingFace);\n    }\n\n    function consumeImpairment(\n        ReserveManager.ReserveStorage storage $,\n        uint256 facilityId,\n        uint256 recognized,\n        uint256 consumed\n    ) internal {\n        uint256 facilityImpairment = recognized - consumed;\n        $.principalImpairment[facilityId] = facilityImpairment;\n        uint256 total = $.totalPrincipalImpairment - consumed;\n        $.totalPrincipalImpairment = total;\n        emit IReserveManager.PrincipalImpairmentRealized(facilityId, consumed, facilityImpairment, total);\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.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 Mints shares Vault shares to receiver by depositing exactly amount of 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\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 by depositing amount of 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"},{"file_path":"src/libraries/ReserveRoundingLib.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {ReserveManager} from \"../ReserveManager.sol\";\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {ICuratorModule} from \"../interfaces/ICuratorModule.sol\";\nimport {IMintRedeemController} from \"../interfaces/IMintRedeemController.sol\";\nimport {IsUSDfr} from \"../interfaces/IsUSDfr.sol\";\nimport {IReserveManager} from \"../interfaces/IReserveManager.sol\";\nimport {IAccrualRoundingRisk, IAccrualRoundingRegistry} from \"../interfaces/IAccrualLifecycle.sol\";\nimport {AccrualBook} from \"./AccrualBook.sol\";\nimport {AccrualLoans} from \"./AccrualLoans.sol\";\nimport {ReserveAccrualStorageLib} from \"./ReserveAccrualStorageLib.sol\";\nimport {ReserveAccrualLib} from \"./ReserveAccrualLib.sol\";\nimport {ReserveStorageLib} from \"./ReserveStorageLib.sol\";\nimport {ReserveCreditLib} from \"./ReserveCreditLib.sol\";\nimport {ICascadeBackstop} from \"../interfaces/ICascadeBackstop.sol\";\n\n/// @title ReserveRoundingLib\n/// @notice Allocates a proved sub-native-unit contractual discrepancy through Ethereum's native three-layer loss order.\n/// @dev Gross earned income and both earned fee claims are retained. This library owns no independent\n///      write-off authority: the reserve supplies its just-derived, nonce-bound lifecycle work.\nlibrary ReserveRoundingLib {\n    /// @dev One in-memory allocation; no independent accounting or storage namespace.\n    struct Allocation {\n        uint256 prepaid;\n        uint256 curator;\n        uint256 backstop;\n        uint256 senior;\n        uint256 unabsorbed;\n        uint256 mark;\n    }\n\n    using AccrualBook for AccrualBook.Book;\n    using ReserveStorageLib for ReserveManager.ReserveStorage;\n\n    error AccrualRounding_InvalidContinuation();\n    error AccrualRounding_DeltaMismatch(uint8 measurement, uint256 expected, uint256 actual);\n    error AccrualRounding_InsufficientGas();\n\n    /// @notice The exact discrepancy, its native loss allocation, and the explicitly unabsorbed remainder.\n    event AccrualRoundingAllocated(\n        uint256 indexed facilityId,\n        uint64 indexed closureNonce,\n        uint256 amount,\n        uint256 prepaid,\n        uint256 curator,\n        uint256 backstop,\n        uint256 senior,\n        uint256 unabsorbed,\n        uint256 markConsumed\n    );\n\n    /// @notice Reconciles interpolation and delivers the vault's pre-loss claims before closing the loan.\n    /// @dev Preparation exposes a coherent pre-loss book; the reserve's outer operation guard remains\n    ///      held. No receipt, basis change, face write-down or burn has occurred during these callbacks.\n    ///      A separate fee recipient retains its earned claim for permissionless delivery. Its transfer\n    ///      restrictions must not block repayment or senior loss allocation. If the vault also owns\n    ///      the fee claim, both legs must be physical before its assets can fund a loss.\n    function prepare(ReserveManager.ReserveStorage storage native, uint256 id) public {\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        AccrualLoans.Loan storage loan = s.loans.loans[id];\n        if (loan.terms.scale == 1 || !s.loans.book.entries[id].scheduled) return;\n        uint64 at = ReserveAccrualStorageLib.now64();\n        s.loans.book.reconcile(id, at);\n        uint256 recognized = s.loans.book.earned(id, at) - loan.segmentBookBase;\n        (uint256 canonical,) = AccrualLoans.canonicalSegment(loan, at);\n        if (recognized <= canonical) return;\n        ReserveAccrualLib.prepareNativeLoss(native);\n        IsUSDfr(s.modules.vault).accrueFees();\n    }\n\n    /// @notice Consumes one armed burn; all unrelated controller operations retain the busy gate.\n    function consumeBurn(address caller, address from, uint256 amount) public returns (bool) {\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        if (msg.sender != s.modules.controller) revert AccrualRounding_InvalidContinuation();\n        ReserveAccrualStorageLib.Rounding storage r = s.rounding;\n        if (!r.active) return false;\n        if (\n            !s.busy || s.delivery.active || !r.ready || caller != address(this) || from != r.from || amount != r.amount\n                || amount == 0\n        ) revert AccrualRounding_InvalidContinuation();\n        r.ready = false;\n        return true;\n    }\n\n    /// @notice Uses prepaid marks, this facility's curator class, then sGROVE and clamped senior assets.\n    function allocate(ReserveManager.ReserveStorage storage native, AccrualLoans.LifecycleWork memory work) public {\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        uint256 loss = work.roundingLoss;\n        AccrualLoans.Loan storage loan = s.loans.loans[work.facilityId];\n        if (\n            !s.busy || s.delivery.active || s.rounding.active || loss == 0 || loss >= loan.terms.scale\n                || work.closureNonce != loan.closureNonce || _unissuedVaultAssets(s, work.at) != 0\n        ) revert AccrualRounding_InvalidContinuation();\n        uint256[5] memory before_ = _measure(s, native);\n        Allocation memory allocation;\n        allocation.mark = native.principalImpairment[work.facilityId];\n        if (allocation.mark > loss) allocation.mark = loss;\n        allocation.prepaid = native.exitPrepaidAbsorption;\n        if (allocation.prepaid > allocation.mark) allocation.prepaid = allocation.mark;\n        if (allocation.prepaid != 0) {\n            native.exitPrepaidAbsorption -= allocation.prepaid;\n            emit IReserveManager.ExitPrepaymentConsumed(\n                work.facilityId, allocation.prepaid, native.exitPrepaidAbsorption\n            );\n        }\n        s.rounding.facilityId = work.facilityId;\n        s.rounding.closureNonce = work.closureNonce;\n        s.rounding.active = true;\n        allocation.curator = _curator(s, native, work.facilityId, loss - allocation.prepaid);\n        allocation.backstop = _backstop(s, native, work.facilityId, loss - allocation.prepaid - allocation.curator);\n        if (allocation.curator + allocation.backstop != 0) {\n            _burn(s, address(this), allocation.curator + allocation.backstop);\n        }\n        allocation.senior = loss - allocation.prepaid - allocation.curator - allocation.backstop;\n        uint256 available = IsUSDfr(s.modules.vault).totalAssets();\n        if (allocation.senior > available) allocation.senior = available;\n        if (allocation.senior != 0) _burn(s, s.modules.vault, allocation.senior);\n        allocation.unabsorbed = loss - allocation.prepaid - allocation.curator - allocation.backstop - allocation.senior;\n        s.roundingUnabsorbed += allocation.unabsorbed;\n        ReserveCreditLib.writeDown(native, work.facilityId, loss);\n        s.recordedFace -= loss;\n        _notify(s, work.facilityId, loss);\n        uint256[5] memory after_ = _measure(s, native);\n        _equal(0, before_[0] - allocation.curator - allocation.backstop - allocation.senior, after_[0]);\n        _equal(1, before_[1], after_[1]);\n        _equal(2, before_[2] - allocation.senior, after_[2]);\n        uint256 reduction = loss - allocation.mark;\n        _equal(3, before_[3] > reduction ? before_[3] - reduction : 0, after_[3]);\n        _equal(7, before_[4], after_[4]); // Outstanding fee claims are neither canceled nor spent.\n        delete s.rounding;\n        emit AccrualRoundingAllocated(\n            work.facilityId,\n            work.closureNonce,\n            loss,\n            allocation.prepaid,\n            allocation.curator,\n            allocation.backstop,\n            allocation.senior,\n            allocation.unabsorbed,\n            allocation.mark\n        );\n    }\n\n    function _curator(\n        ReserveAccrualStorageLib.State storage s,\n        ReserveManager.ReserveStorage storage native,\n        uint256 id,\n        uint256 loss\n    ) private returns (uint256 absorbed) {\n        if (loss == 0) return 0;\n        uint256 classId = s.identities[id].classId;\n        ICuratorModule curator = native.lossCurator;\n        uint256 expected = curator.poolBalance(classId);\n        if (expected > loss) expected = loss;\n        uint256 before_ = IERC20(s.modules.token).balanceOf(address(this));\n        uint256 residual;\n        (absorbed, residual) = curator.absorbLoss{gas: _forwardGas()}(classId, loss);\n        _equal(4, expected, absorbed);\n        _equal(5, loss - absorbed, residual);\n        _equal(6, before_ + absorbed, IERC20(s.modules.token).balanceOf(address(this)));\n    }\n\n    /// @dev sGROVE's recorded executable reserve is drawn only after this class's curator capital.\n    function _backstop(\n        ReserveAccrualStorageLib.State storage s,\n        ReserveManager.ReserveStorage storage native,\n        uint256 id,\n        uint256 loss\n    ) private returns (uint256 covered) {\n        if (loss == 0) return 0;\n        ICascadeBackstop backstop = native.lossBackstop;\n        uint256 expected = backstop.remainingCoverage(id);\n        if (expected > loss) expected = loss;\n        uint256 balance = IERC20(s.modules.token).balanceOf(address(this));\n        covered = backstop.coverShortfall{gas: _forwardGas()}(id, loss);\n        _equal(8, expected, covered);\n        _equal(9, balance + covered, IERC20(s.modules.token).balanceOf(address(this)));\n    }\n\n    function _burn(ReserveAccrualStorageLib.State storage s, address from, uint256 amount) private {\n        s.rounding.from = from;\n        s.rounding.amount = amount;\n        s.rounding.ready = true;\n        IMintRedeemController(s.modules.controller).burnLoss{gas: _forwardGas()}(from, amount);\n        if (s.rounding.ready) revert AccrualRounding_InvalidContinuation();\n    }\n\n    function _notify(ReserveAccrualStorageLib.State storage s, uint256 id, uint256 amount) private {\n        ReserveAccrualStorageLib.Identity storage identity = s.identities[id];\n        IAccrualRoundingRegistry(s.modules.registry).recordAccruedWriteDown(\n            identity.classId, identity.borrowerId, identity.stateId, amount\n        );\n        IAccrualRoundingRisk(s.modules.defaultManager).onAccrualRounding(id, amount);\n    }\n\n    function _measure(ReserveAccrualStorageLib.State storage s, ReserveManager.ReserveStorage storage native)\n        private\n        view\n        returns (uint256[5] memory values)\n    {\n        IERC20 token = IERC20(s.modules.token);\n        values[0] = token.totalSupply();\n        values[1] = token.balanceOf(address(this));\n        values[2] = token.balanceOf(s.modules.vault);\n        values[3] = native.backingValue();\n        values[4] = s.loans.book.snapshot(ReserveAccrualStorageLib.now64()).unissued;\n    }\n\n    function _unissuedVaultAssets(ReserveAccrualStorageLib.State storage s, uint64 at)\n        private\n        view\n        returns (uint256 owned)\n    {\n        AccrualBook.Snapshot memory claims = s.loans.book.snapshot(at);\n        owned = claims.seniorUnissued;\n        if (s.feeRecipient == s.modules.vault) owned += claims.feeUnissued;\n    }\n\n    function _forwardGas() private view returns (uint256) {\n        uint256 available = gasleft();\n        uint256 retained = available >> 3;\n        if (retained < 450_000) retained = 450_000;\n        if (available <= retained + 200_000) revert AccrualRounding_InsufficientGas();\n        return available - retained;\n    }\n\n    function _equal(uint8 measurement, uint256 expected, uint256 actual) private pure {\n        if (expected != actual) revert AccrualRounding_DeltaMismatch(measurement, expected, actual);\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/math/Math.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.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 `a ? b : c`. 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. `a ? b : c`) 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"},{"file_path":"src/interfaces/IAccrualLifecycle.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\n/// @title IAccrualLifecycle\n/// @notice Authenticated loan events consumed by the reserve's continuous accounting book.\n/// @dev These methods accept no caller-selected accounting timestamp or interest correction.\ninterface IAccrualLifecycle {\n    /// @notice Supported forward fixed-rate terms, projected from a consumed bridge amendment.\n    struct Terms {\n        uint16 rateBps;\n        uint32 yearSeconds;\n        uint64 nextPaymentDue;\n        uint64 paymentInterval;\n        uint64 maturity;\n    }\n\n    /// @notice Prospective fixed Actual/360 terms for one concurrent cash/PIK facility.\n    struct MixedTerms {\n        uint16 cashRateBps;\n        uint16 pikRateBps;\n        uint32 yearSeconds;\n        uint64 nextPikCapitalization;\n        uint64 pikCapitalizationInterval;\n        uint64 maturity;\n    }\n\n    /// @notice Contractual debt, separately disclosed from the reserve's streamed accounting face.\n    struct Debt {\n        uint256 principal;\n        uint256 interest;\n        uint256 balanceCeiling;\n        uint64 accruedThrough;\n        uint64 nextCapitalization;\n        uint64 maturity;\n        bool pik;\n        bool active;\n        bool known;\n    }\n\n    /// @notice Current unpaid interest separated by its legal settlement leg.\n    /// @dev `mixed` distinguishes a concurrent facility from the equivalent balances on a\n    ///      one-leg note. Unknown or disabled records return the all-zero shape.\n    struct InterestLegs {\n        uint256 cash;\n        uint256 pik;\n        uint64 accruedThrough;\n        bool mixed;\n        bool known;\n    }\n\n    /// @notice Registers the bound waterfall's just-funded, authenticated bridge facility.\n    function registerAccruingLoan(uint256 facilityId) external;\n\n    /// @notice Processes a bounded number of chronological due events; partial progress persists.\n    function checkpointAccrual(uint256 maximum) external returns (uint256 processed, bool fresh);\n\n    /// @notice Transfers one facility's existing virtual receivable into its native face ledger.\n    function postAccruedLoan(uint256 facilityId) external returns (uint256 amount);\n\n    /// @notice Applies the bridge's consumed, authenticated amendment prospectively.\n    function amendAccruingLoan(uint256 facilityId, Terms calldata terms) external;\n\n    /// @notice Applies the bridge's consumed, authenticated two-leg amendment prospectively.\n    function amendMixedAccruingLoan(uint256 facilityId, MixedTerms calldata terms) external;\n\n    /// @notice Aligns and permanently stops the facility before its default declaration snapshot.\n    function stopAccruingLoan(uint256 facilityId) external;\n\n    /// @notice Changes only the bound default manager's growing past-due cohort membership.\n    function setAccrualPastDue(uint256 facilityId, bool marked) external;\n\n    /// @notice Contractual debt through the capped, coherent portfolio frontier, in constant time.\n    function accruedDebt(uint256 facilityId) external view returns (Debt memory);\n\n    /// @notice Current cash-pay and PIK balances through the same coherent frontier, in constant time.\n    function accruedInterestLegs(uint256 facilityId) external view returns (InterestLegs memory);\n\n    /// @notice Additional unposted interest on a class's marked past-due cohort.\n    function accruedPastDue(uint256 classId) external view returns (uint256 amount);\n\n    /// @notice Streamed book face not yet posted for one facility; distinct from canonical interest.\n    function unpostedAccruedLoan(uint256 facilityId) external view returns (uint256 amount);\n}\n\n/// @notice The reserve alone advances already signed PIK capitalization boundaries.\ninterface IAccrualBridge {\n    function setAccruedPaymentDue(uint256 facilityId, uint64 nextDue) external;\n}\n\n/// @notice Narrow notification of a posted receivable already counted in effective exposure.\ninterface IAccrualRegistry {\n    function recordAccruedExposure(uint256 classId, bytes32 borrowerId, bytes32 stateId, uint256 amount) external;\n}\n\n/// @notice Moves already-counted cohort growth into the default manager's recorded risk carrier.\ninterface IAccrualRisk {\n    function onAccrualPosted(uint256 facilityId, uint256 amount) external;\n}\n\n/// @notice The waterfall changes its standing interest fee only prospectively.\ninterface IAccrualFeeConfig {\n    function setAccrualFee(uint16 feeBps, address recipient) external;\n}\n\n/// @notice Constant-time servicing of signed dates with no positive queued accrual work.\ninterface IAccrualServicing {\n    function serviceAccruedLoan(uint256 facilityId) external returns (uint256 capitalized);\n    function accrualLoanScheduled(uint256 facilityId) external view returns (bool);\n}\n\n/// @notice Explicit native loss allocation of an independently derived sub-unit discrepancy.\ninterface IAccrualRounding {\n    /// @notice Monotone unabsorbed contractual rounding loss, never caller-selected debt relief.\n    function roundingLossUnabsorbed() external view returns (uint256);\n\n    /// @notice Controller-only consumption of one exact reserve-owned physical burn permit.\n    /// @dev Returns false outside a rounding continuation; normal loss admission then applies.\n    function consumeAccrualLossBurn(address caller, address from, uint256 amount) external returns (bool);\n}\n\n/// @notice The reserve reduces only a marked contribution whose face it has actually written down.\ninterface IAccrualRoundingRisk {\n    function onAccrualRounding(uint256 facilityId, uint256 amount) external;\n}\n\n/// @notice Registry continuation paired with a reserve-proved native rounding write-down.\ninterface IAccrualRoundingRegistry {\n    function recordAccruedWriteDown(uint256 classId, bytes32 borrowerId, bytes32 stateId, uint256 amount) external;\n}\n\n/// @notice Measured receipt settlement and terminal retirement, separately bound to servicing modules.\ninterface IAccrualReceipts {\n    /// @notice Measures an attested receipt and discharges separately tracked principal and interest.\n    function repayAccruingLoan(uint256 facilityId, address payer, uint256 principal, uint256 interest)\n        external\n        returns (uint256 outstanding);\n\n    /// @notice Releases a fully extinguished, resolved facility's active-book slot after its risk hooks.\n    function retireAccruedLoan(uint256 facilityId) external;\n}\n"},{"file_path":"src/interfaces/ICuratorModule.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\n/// @title ICuratorModule — per-class curator first-loss vaults (ADR-0004)\n/// @notice Curators (anchor: Forest Road, $10M/class default; additional curators\n///         pluggable per class) post USDfr first-loss capital that absorbs realized\n///         losses BEFORE the sGROVE backstop and depositor principal (CLAUDE.md §1.3\n///         cascade ordering). Multi-curator stakes in one class share losses exactly\n///         pro-rata via internal shares. Withdrawals are constrained by subordination\n///         headroom: posted capital protecting live exposure cannot leave.\ninterface ICuratorModule {\n    // ── Events ───────────────────────────────────────────────────────────\n    event CuratorApproved(uint256 indexed classId, address indexed curator, bool approved);\n    event FirstLossTargetSet(uint256 indexed classId, uint256 target);\n    // `round` disambiguates share attribution across a wipe-out (audit fix, §3.1).\n    event FirstLossPosted(\n        uint256 indexed classId, address indexed curator, uint256 amount, uint256 shares, uint256 round\n    );\n    event FirstLossWithdrawn(\n        uint256 indexed classId, address indexed curator, uint256 amount, uint256 shares, uint256 round\n    );\n    /// @notice Emitted on every cascade layer-1 absorption (residual > 0 escalates).\n    event LossAbsorbed(uint256 indexed classId, uint256 loss, uint256 absorbed, uint256 residual);\n    /// @notice Emitted when a fully-wiped class pool restarts a new share round.\n    event PoolRoundAdvanced(uint256 indexed classId, uint256 newRound);\n    /// @notice Share units were divided by a power of two to retain representability.\n    event PoolSharesNormalized(uint256 indexed classId, uint256 shift, uint256 totalShares);\n    /// @notice AUDIT FIX (SWEEP-4 S4-R1). A round was CLOSED as economically wiped while a\n    ///         residual balance still stood, so the residual's ownership was snapshotted for the\n    ///         closing cohort instead of being forfeited to the pool.\n    /// @param classId The class whose round closed.\n    /// @param closedRound The round that closed.\n    /// @param residual The USDfr still standing in the pool at the close.\n    /// @param closedShares Shares of the closed round that share `residual` pro-rata.\n    /// @param carriedShares Shares of the SUCCEEDING round the closed cohort collectively owns\n    ///        (equal to `residual`, because the new round opens at a share price of exactly 1).\n    event ClosedRoundSnapshotted(\n        uint256 indexed classId,\n        uint256 indexed closedRound,\n        uint256 residual,\n        uint256 closedShares,\n        uint256 carriedShares\n    );\n    /// @notice AUDIT FIX (SWEEP-4 S4-R1). A curator's stale-round stake was walked forward through\n    ///         one or more CLOSED rounds. `settledShares == 0` means the stale stake was genuinely\n    ///         worth nothing and was cleared; `toRound` below the class's live round means the walk\n    ///         hit `MAX_CLOSED_ROUND_HOPS` and `claimClosedRound` must be called again.\n    /// @param classId The class whose stake was settled.\n    /// @param curator The stake's owner (the settler may be anyone).\n    /// @param fromRound The round the stake held before the walk.\n    /// @param toRound The round the stake holds after it.\n    /// @param staleShares Shares held at `fromRound`.\n    /// @param settledShares Shares held at `toRound`.\n    event ClosedRoundSettled(\n        uint256 indexed classId,\n        address indexed curator,\n        uint256 indexed fromRound,\n        uint256 toRound,\n        uint256 staleShares,\n        uint256 settledShares\n    );\n    /// @notice Emitted when a default entering a class freezes curator withdrawals.\n    ///         `count` is the number of unresolved defaults now outstanding on the class.\n    event ClassDefaultFrozen(uint256 indexed classId, uint256 count);\n    /// @notice Emitted when governance lifts one default freeze from a class.\n    event ClassDefaultFreezeLifted(uint256 indexed classId, uint256 count);\n    /// @notice AUDIT FIX (R6-CF1). The ReserveManager whose custody-loss window gates withdrawals.\n    event ReserveManagerUpdated(address indexed reserves);\n    /// @notice AUDIT FIX (R6-CF1). The governor the pre-arm duration is derived from (0 = the\n    ///         `Config` launch parameters are used as the floor and nothing overrides them).\n    event GovernorUpdated(address indexed governor);\n    /// @notice AUDIT FIX (R6-CF1). A guardian armed the custody freeze ahead of governance.\n    /// @param guardian The arming guardian.\n    /// @param expiry Unix time at which the pre-arm lapses on its own.\n    /// @param count Consecutive pre-arms used out of the budget, after this one.\n    event CustodyFreezePreArmed(address indexed guardian, uint64 expiry, uint32 count);\n    /// @notice AUDIT FIX (R6-CF1). Governance declared a FALSE ALARM: the guardian pre-arm limb is\n    ///         cleared and the budget replenished. This can NEVER release a genuine custody freeze\n    ///         — the derived limbs in `IReserveManager.custodyLossUnabsorbed` stand on their own.\n    event CustodyFreezePreArmCancelled(uint64 previousExpiry);\n    /// @notice AUDIT FIX (F3-PA-a). Governance replenished the guardian's pre-arm budget while\n    ///         LEAVING the standing pre-arm in force — \"we looked, the incident is real, keep\n    ///         going\". `expiry` is echoed unchanged precisely so an observer can verify that the\n    ///         protection survived the replenishment.\n    /// @param spent Budget units returned to the guardian.\n    /// @param expiry The standing pre-arm expiry, unchanged by this call.\n    event CustodyFreezePreArmBudgetReplenished(uint32 spent, uint64 expiry);\n    /// @notice AUDIT FIX (F3-PA-b). A previous pre-arm had lapsed and layer-1 capital had stood\n    ///         unfrozen for the full `custodyPreArmCooldown()`, so the consecutive counter reset\n    ///         and this arm opened a NEW episode.\n    /// @param spent Budget the lapsed episode had used.\n    /// @param lapsedExpiry Expiry of the episode that just ended.\n    event CustodyFreezePreArmEpisodeReset(uint32 spent, uint64 lapsedExpiry);\n    /// @notice AUDIT FIX (F3-PA-c). THE CAP BOUND. One pre-arm window no longer outlasts the live\n    ///         governance path, so the freeze WILL lapse before governance can ratify it unless\n    ///         `replenishCustodyPreArmBudget` carries it. Emitted at the arm so the condition can\n    ///         never arise silently; `script/Validate.s.sol` refuses a deployment in this regime.\n    /// @param livePath The unbounded `votingDelay + votingPeriod + minDelay` reading, in seconds.\n    /// @param duration The window actually granted, bounded by `CUSTODY_PRE_ARM_MAX_PATH`.\n    /// @param count Consecutive pre-arms used out of the budget, after this one.\n    event CustodyFreezePreArmTruncated(uint256 livePath, uint64 duration, uint32 count);\n\n    // ── Errors ───────────────────────────────────────────────────────────\n    error Curator_ZeroAddress();\n    error Curator_ZeroAmount();\n    /// @notice The proposed points module has no code. Refused for the same reason\n    ///         `USDfr.setPointsModule` refuses it (C4-USDFR-01): the points hooks return no\n    ///         data, so solc emits an `extcodesize` guard that reverts OUTSIDE the fail-open\n    ///         `try` — turning a hook that must never block the cascade into one that always\n    ///         does. See P-48b.\n    /// @param module The codeless address that was refused.\n    error Curator_PointsModuleNotAContract(address module);\n    error Curator_UnknownClass(uint256 classId);\n    error Curator_NotApprovedCurator(uint256 classId, address curator);\n    error Curator_InsufficientStake(uint256 classId, address curator, uint256 requested, uint256 posted);\n    error Curator_HeadroomExceeded(uint256 classId, uint256 requested, uint256 headroom);\n    /// @notice Withdrawals are frozen because the class has an unresolved default\n    ///         (audit R4-EC2: stops a curator front-running realizeLoss to duck a loss).\n    error Curator_ClassDefaultFrozen(uint256 classId);\n    /// @notice liftDefaultFreeze called on a class with no outstanding default freeze.\n    error Curator_NotFrozen(uint256 classId);\n    /// @notice AUDIT FIX (R6-CF1). Withdrawals are frozen because a reserve-CUSTODY loss is\n    ///         recognised, observable or incompletely absorbed, or because a guardian has\n    ///         pre-armed the freeze. Curator capital is cascade LAYER 1 for that loss and may not\n    ///         exit ahead of it — the custody twin of `Curator_ClassDefaultFrozen` (R4-EC2).\n    error Curator_CustodyLossFrozen();\n    /// @notice AUDIT FIX (R6-CF1). No ReserveManager is wired, so the custody-loss window cannot\n    ///         be evaluated. Withdrawals fail CLOSED rather than proceeding blind.\n    error Curator_ReserveNotWired();\n    /// @notice AUDIT FIX (R6-CF1). The guardian's consecutive pre-arm budget is spent. Only\n    ///         governance can replenish it, which is what bounds a unilateral guardian freeze.\n    error Curator_PreArmBudgetExhausted(uint32 requested, uint32 max);\n    /// @notice AUDIT FIX (R6-CF1). `cancelCustodyPreArm` with nothing armed and no budget used.\n    error Curator_NoPreArm();\n    /// @notice AUDIT FIX (R6-CF1). `setReserveManager` was given an address that is not a\n    ///         ReserveManager. Wiring the freeze to the wrong contract would make the guard read\n    ///         someone else's state, so this fails loudly rather than accepting it.\n    error Curator_InvalidReserveManager(address reserves);\n    /// @notice AUDIT FIX (R6-CF1). `setGovernor` was given an address with no code, which could\n    ///         never supply a live governance path.\n    error Curator_InvalidGovernor(address governor);\n    error Curator_ReserveManagerChangeFrozen();\n    error Curator_ReserveLossWithdrawalsFrozen();\n    error Curator_ShareCapacityExceeded(uint256 amount, uint256 availableShares);\n    /// @notice AUDIT FIX (SWEEP-4 S4-R1). The caller holds a stake in a round that closed more than\n    ///         one round ago, so a single conversion cannot bring it to the live round. Call\n    ///         `claimClosedRound` (permissionless) until `stakeRound == liveRound`, then retry.\n    ///         Posting or withdrawing is REFUSED rather than silently erasing the residual claim.\n    error Curator_UnsettledClosedRound(uint256 classId, uint256 stakeRound, uint256 liveRound);\n\n    // ── Curator paths ────────────────────────────────────────────────────\n    /// @notice Posts `amount` USDfr of first-loss capital to `classId`'s pool.\n    ///         Caller must be an approved curator for the class.\n    function postFirstLoss(uint256 classId, uint256 amount) external;\n\n    /// @notice Withdraws `amount` USDfr of the caller's stake, capped by BOTH the\n    ///         caller's pro-rata stake and the class's subordination headroom.\n    function withdrawFirstLoss(uint256 classId, uint256 amount) external;\n\n    /// @notice AUDIT FIX (SWEEP-4 S4-R1). Converts `curator`'s stake in a CLOSED round into its\n    ///         pro-rata slice of the succeeding round's shares. PERMISSIONLESS — anyone may settle\n    ///         anyone, because a curator who cannot settle cannot post or withdraw either, and\n    ///         layer-1 liveness must not depend on one address being available.\n    /// @dev Moves NO value: the shares it assigns were minted at the close and have been part of\n    ///      `poolShares(classId)` ever since. It is a pure re-attribution of ownership, which is why\n    ///      it is not pausable and not gated by either withdrawal freeze — neither of those governs\n    ///      attribution, and both still bind on `withdrawFirstLoss`.\n    ///      Idempotent: a stake already on the live round is a no-op. Call it repeatedly to walk a\n    ///      stake through several consecutive closes.\n    function claimClosedRound(uint256 classId, address curator) external;\n\n    // ── Cascade (credit layer only) ──────────────────────────────────────\n    /// @notice Absorbs up to `loss` from the class pool (cascade layer 1). Transfers\n    ///         the absorbed USDfr to `msg.sender` (the DefaultManager), which burns it\n    ///         in the same transaction against the principal write-down (ADR-0012).\n    /// @return absorbed Amount taken from the pool (== min(loss, pool balance)).\n    /// @return residual Loss remaining for the next cascade layer.\n    function absorbLoss(uint256 classId, uint256 loss) external returns (uint256 absorbed, uint256 residual);\n\n    /// @notice Absorbs a classless protocol loss across all five pools, weighted by balances\n    ///         snapshotted before any pool is changed. Rounding dust is assigned deterministically\n    ///         to the lowest-numbered non-empty pools with snapshot headroom.\n    /// @dev Transfers the aggregate absorbed USDfr to the caller for same-transaction burning.\n    function absorbGlobalLoss(uint256 loss) external returns (uint256 absorbed, uint256 residual);\n\n    // ── Default freeze (audit R4-EC2) ────────────────────────────────────\n    /// @notice Records that a facility in `classId` has entered default, freezing curator\n    ///         withdrawals for the class until governance lifts it. Called by the\n    ///         DefaultManager (CREDIT_ROLE) on declareDefault / liquidate. Increments an\n    ///         unresolved-default counter so concurrent defaults each require a lift.\n    function freezeOnDefault(uint256 classId) external;\n\n    /// @notice Governance (timelock) lifts one default freeze from `classId` once a\n    ///         workout resolves. Reverts if the class has no outstanding freeze.\n    function liftDefaultFreeze(uint256 classId) external;\n\n    /// @notice Number of unresolved defaults freezing withdrawals on a class (0 = open).\n    function unresolvedDefaults(uint256 classId) external view returns (uint256);\n\n    // ── Custody-loss freeze (audit R6-CF1) ───────────────────────────────\n\n    /// @notice AUDIT FIX (R6-CF1). True while curator first-loss capital is frozen by a\n    ///         reserve-CUSTODY loss (recognised, observable, or incompletely absorbed) or by a\n    ///         live guardian pre-arm. Class-independent: a custody loss is allocated across ALL\n    ///         five pools by `absorbGlobalLoss`, so the freeze is protocol-wide.\n    /// @dev Reads as TRUE when no ReserveManager is wired. \"Cannot tell\" must never read as\n    ///      \"clear\" on a guard whose whole job is to stop capital leaving ahead of a loss.\n    function custodyFreezeActive() external view returns (bool);\n\n    /// @notice AUDIT FIX (R6-CF1). Guardian arms the custody freeze ahead of governance, for\n    ///         losses that are known but not yet visible on-chain (a custodian insolvency, a legal\n    ///         seizure, an off-chain balance frozen). A guardian may ARM but has NO release.\n    function preArmCustodyFreeze() external;\n\n    /// @notice AUDIT FIX (R6-CF1). Governance declares a FALSE ALARM: clears the guardian pre-arm\n    ///         limb and replenishes the pre-arm budget.\n    /// @dev It CANNOT release a real custody freeze: the derived limbs are unaffected. That is why\n    ///      giving governance this cancel does not hand it a loss-dodging lever.\n    ///\n    ///      AUDIT FIX (F3-PA-a). This is the FALSE-ALARM lever only. To keep a REAL incident frozen\n    ///      while returning budget to the guardian, use `replenishCustodyPreArmBudget` — using this\n    ///      one for that purpose destroys the protection it was called to extend.\n    function cancelCustodyPreArm() external;\n\n    /// @notice AUDIT FIX (F3-PA-a). Governance returns the guardian's pre-arm budget WITHOUT\n    ///         touching the standing pre-arm — \"we looked, the incident is real, keep going\".\n    /// @dev THE HIGH THIS CLOSES: `cancelCustodyPreArm` was the only replenishment path and it\n    ///      zeroes `custodyPreArmExpiry`, so regaining budget destroyed the active protection and\n    ///      opened a window in which curator first-loss could leave ahead of a loss it is cascade\n    ///      LAYER 1 for. Reverts with `Curator_NoPreArm` when no budget has been spent.\n    function replenishCustodyPreArmBudget() external;\n\n    /// @notice AUDIT FIX (R6-CF1). Current guardian pre-arm: lapse time and CONSECUTIVE budget used\n    ///         within the current episode (see `custodyPreArmCooldown`).\n    function custodyPreArm() external view returns (uint64 expiry, uint32 count);\n\n    /// @notice AUDIT FIX (R6-CF1). How long one guardian pre-arm lasts. DERIVED from the live\n    ///         governance path (`votingDelay + votingPeriod + timelock minDelay`) with the `Config`\n    ///         launch parameters as a floor, so it can never expire before governance could\n    ///         possibly have ratified it.\n    /// @dev Strictly greater than `custodyPreArmGovernancePath()` at every parameterisation.\n    function custodyPreArmDuration() external view returns (uint64);\n\n    /// @notice AUDIT FIX (F3-PA-c). The governance path the duration was derived from: the longer\n    ///         of the `Config` launch floor and the live reading, bounded by\n    ///         `CUSTODY_PRE_ARM_MAX_PATH`.\n    function custodyPreArmGovernancePath() external view returns (uint64);\n\n    /// @notice AUDIT FIX (F3-PA-c). False when the path bound BINDS — i.e. one pre-arm window no\n    ///         longer outlasts the LIVE governance path and `replenishCustodyPreArmBudget` must\n    ///         carry the difference. `script/Validate.s.sol` refuses a deployment where this is\n    ///         false, and `preArmCustodyFreeze` emits `CustodyFreezePreArmTruncated` when it arms\n    ///         into that regime.\n    function custodyPreArmCoversLiveGovernancePath() external view returns (bool);\n\n    /// @notice AUDIT FIX (F3-PA-b). How long layer-1 capital must stand UNFROZEN after a pre-arm\n    ///         lapses before the guardian's consecutive budget resets and a new episode may open.\n    function custodyPreArmCooldown() external view returns (uint64);\n\n    /// @notice AUDIT FIX (R6-CF1). Wires the ReserveManager whose custody-loss window gates\n    ///         withdrawals. Timelocked governance only; zero explicitly unwires (and freezes).\n    function setReserveManager(address reserves) external;\n\n    /// @notice AUDIT FIX (R6-CF1). Wires the governor the pre-arm duration is derived from. Zero\n    ///         leaves the `Config` launch parameters standing as the sole source.\n    function setGovernor(address governor) external;\n    function governanceUnpause() external;\n\n    // ── Views ────────────────────────────────────────────────────────────\n    /// @notice Current pool balance for a class (18-dec USDfr).\n    function poolBalance(uint256 classId) external view returns (uint256);\n\n    /// @notice A curator's current pro-rata stake value in a class.\n    /// @dev AUDIT FIX (SWEEP-4 S4-R1, FOUR-INPUT COMPOSITION). Live-round values are exact. A\n    ///      closed-round value is a conservative pre-settlement quote because the executable\n    ///      remaining/remaining allocation depends on settlement order. Partial holders round\n    ///      down; only the unique holder of a snapshot's whole remaining cohort may receive its\n    ///      one-unit remainder. It may read zero for sub-wei carry or beyond the bounded walk\n    ///      without erasing the claim; call `claimClosedRound` to materialize the exact live stake.\n    function postedOf(uint256 classId, address curator) external view returns (uint256);\n\n    /// @notice AUDIT FIX (SWEEP-4 S4-R1). The residual-claim snapshot for a CLOSED round.\n    /// @param classId The class.\n    /// @param round The closed round.\n    /// @return closedShares Shares of `round` that have not yet been settled.\n    /// @return carriedShares Shares of round `round + 1` those unsettled shares collectively own.\n    function closedRound(uint256 classId, uint256 round)\n        external\n        view\n        returns (uint256 closedShares, uint256 carriedShares);\n\n    /// @notice Required subordination for a class: min(first-loss target, live class\n    ///         exposure). Capital up to this level cannot be withdrawn.\n    function requiredFirstLoss(uint256 classId) external view returns (uint256);\n\n    /// @notice Withdrawable excess above the subordination requirement.\n    function headroom(uint256 classId) external view returns (uint256);\n\n    /// @notice Governance-set first-loss target for a class (ADR-0004: $10M default).\n    function firstLossTarget(uint256 classId) external view returns (uint256);\n\n    /// @notice True if `curator` may post first-loss to `classId`.\n    function isApprovedCurator(uint256 classId, address curator) external view returns (bool);\n\n    function reserveManager() external view returns (address);\n    function modules() external view returns (address usdfr, address registry, address feeVault);\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.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        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\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        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\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 _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));\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 _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));\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        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n        if (!_callOptionalReturnBool(token, approvalCall)) {\n            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n            _callOptionalReturn(token, approvalCall);\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 rely 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 rely 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     * Opposedly, 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 high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        uint256 returnSize;\n        uint256 returnValue;\n        assembly (\"memory-safe\") {\n            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n            // bubble errors\n            if iszero(success) {\n                let ptr := mload(0x40)\n                returndatacopy(ptr, 0, returndatasize())\n                revert(ptr, returndatasize())\n            }\n            returnSize := returndatasize()\n            returnValue := mload(0)\n        }\n\n        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.\n     */\n    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n        bool success;\n        uint256 returnSize;\n        uint256 returnValue;\n        assembly (\"memory-safe\") {\n            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n            returnSize := returndatasize()\n            returnValue := mload(0)\n        }\n        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);\n    }\n}\n"},{"file_path":"src/interfaces/ICascadeBackstop.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\n\n/// @title ICascadeBackstop — layer 2 of the loss cascade (ADR-0014)\n/// @notice The sGROVE backstop's loss-absorption surface. Losses flow: curator\n///         first-loss → THIS backstop → sUSDfr (depositor) principal, in that order,\n///         never skipping or inverting a layer (CLAUDE.md §1.3).\n/// @dev CONTRACT WITH THE CALLER (DefaultManager): `coverShortfall` MUST transfer\n///      exactly `covered` USDfr to `msg.sender` before returning, and `covered <=\n///      amount`. The caller burns that USDfr in the same transaction so the supply\n///      reduction matches the principal write-down (ADR-0012). The real implementation\n///      arrives with Phase H (sGROVE); Phase E tests wire a mock honoring this exact\n///      contract, mirroring the MockAttestationOracle pattern from Phase D.\ninterface ICascadeBackstop is IERC165 {\n    /// @notice Emitted for every coverage draw, including zero-coverage responses.\n    event ShortfallCovered(address indexed caller, uint256 requested, uint256 covered);\n\n    /// @notice Covers up to `amount` of a realized shortfall from backstop capital.\n    /// @param eventId Identifies the loss event for durable observability. ADR-0035 deliberately\n    ///        gives this key no separate ceiling or reserved allowance.\n    /// @param amount The shortfall remaining after curator first-loss absorption.\n    /// @return covered USDfr actually provided (transferred to `msg.sender`); the\n    ///         implementation bounds this only by the live coverage reserve, so it may be less\n    ///         than `amount`. Under ADR-0035 one event may exhaust layer two entirely; subsequent\n    ///         loss reaches senior principal until real USDfr replenishes the reserve.\n    function coverShortfall(uint256 eventId, uint256 amount) external returns (uint256 covered);\n\n    /// @notice The whole live USDfr reserve available to the next reported shortfall.\n    /// @dev ADR-0035 removes the former per-event ceiling. This value is therefore identical to\n    ///      `coverageReserve()` and can fall to zero after one event.\n    function coverageCapacity() external view returns (uint256);\n\n    /// @notice Compatibility view for counterfactual accounting; uncapped capacity equals reserve.\n    /// @param reserve The hypothetical live reserve.\n    function coverageCapacityAt(uint256 reserve) external view returns (uint256);\n\n    /// @notice Compatibility parameters for consumers that still express capacity as a formula.\n    /// @dev ADR-0035 fixes these to `(BPS, type(uint256).max)`, the identity function. They are not\n    ///      governance parameters and do not create a per-event ceiling.\n    function coverageCapParameters() external view returns (uint16 proportionalBps, uint256 absoluteCap);\n\n    /// @notice The full USDfr reserve currently held for coverage.\n    function coverageReserve() external view returns (uint256);\n\n    /// @notice The shared live reserve an event would reach if processed next.\n    /// @dev Every event id returns the same value: ADR-0035 creates no event-owned commitment.\n    /// @param eventId Retained for ABI compatibility and observability; it does not affect capacity.\n    /// @return remaining The current shared coverage reserve.\n    function remainingCoverage(uint256 eventId) external view returns (uint256 remaining);\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/access/IAccessControl.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)\n\npragma solidity >=0.8.4;\n\n/**\n * @dev External interface of AccessControl declared to support ERC-165 detection.\n */\ninterface IAccessControl {\n    /**\n     * @dev The `account` is missing a role.\n     */\n    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);\n\n    /**\n     * @dev The caller of a function is not the expected one.\n     *\n     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.\n     */\n    error AccessControlBadConfirmation();\n\n    /**\n     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n     *\n     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n     * {RoleAdminChanged} not being emitted to signal this.\n     */\n    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n    /**\n     * @dev Emitted when `account` is granted `role`.\n     *\n     * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).\n     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.\n     */\n    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Emitted when `account` is revoked `role`.\n     *\n     * `sender` is the account that originated the contract call:\n     *   - if using `revokeRole`, it is the admin role bearer\n     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)\n     */\n    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) external view returns (bool);\n\n    /**\n     * @dev Returns the admin role that controls `role`. See {grantRole} and\n     * {revokeRole}.\n     *\n     * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n     */\n    function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     */\n    function grantRole(bytes32 role, address account) external;\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * If `account` had been granted `role`, emits a {RoleRevoked} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     */\n    function revokeRole(bytes32 role, address account) external;\n\n    /**\n     * @dev Revokes `role` from the calling account.\n     *\n     * Roles are often managed via {grantRole} and {revokeRole}: this function's\n     * purpose is to provide a mechanism for accounts to lose their privileges\n     * if they are compromised (such as when a trusted device is misplaced).\n     *\n     * If the calling account had been granted `role`, emits a {RoleRevoked}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must be `callerConfirmation`.\n     */\n    function renounceRole(bytes32 role, address callerConfirmation) external;\n}\n"},{"file_path":"src/libraries/AccrualSchedule.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\n/// @title AccrualSchedule — one indexed next event per facility\n/// @notice A binary min-heap ordered by (deadline, full-width facility ID).\n/// @dev Count, membership, event lookup and minimum lookup are O(1). Insert, reschedule, keyed\n///      removal and minimum removal are O(log n), without tombstones or a scan over other events.\n///      Zero is a valid facility ID and deadline; every uint256 ID and uint64 deadline is accepted.\n///      The caller owns authorization, contractual chronology, processing capacity and events.\n///      This library reads no clock, makes no external calls and selects no admission policy.\n///      Embed Heap in the host's ERC-7201 storage namespace. Do not directly overwrite its fields\n///      or delete a nonempty Heap: Solidity does not clear mapping entries when deleting a struct.\n///      Existing OpenZeppelin/Solady heaps do not expose indexed keyed removal or swap hooks for\n///      a position map; packing this 320-bit ordering key into uint256 would narrow valid inputs.\nlibrary AccrualSchedule {\n    /// @notice An explicit facility identifier and its next scheduled timestamp.\n    /// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.\n    struct Event {\n        uint256 facilityId;\n        uint64 deadline;\n    }\n\n    /// @notice Heap entries and the one-based position of each scheduled facility.\n    /// @dev Mapping zero means absent; it does not reserve facility ID zero or timestamp zero.\n    ///      No separate storage namespace or initialization transaction is required.\n    /// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.\n    struct Heap {\n        Event[] entries;\n        mapping(uint256 facilityId => uint256 position) positions;\n    }\n\n    /// @notice An empty schedule has no event to inspect or remove.\n    error AccrualSchedule_Empty();\n\n    /// @notice A facility already has its one permitted next event.\n    /// @param facilityId The duplicate identifier; use reschedule to change its deadline.\n    error AccrualSchedule_AlreadyScheduled(uint256 facilityId);\n\n    /// @notice The requested facility has no event in this schedule.\n    /// @param facilityId The missing identifier.\n    error AccrualSchedule_NotScheduled(uint256 facilityId);\n\n    /// @notice Returns the number of scheduled facilities, in O(1).\n    /// @param self The host's schedule.\n    /// @return size Number of live entries; no stale or duplicate entries are retained.\n    function count(Heap storage self) internal view returns (uint256 size) {\n        size = self.entries.length;\n    }\n\n    /// @notice Reports whether a facility has a next event, in O(1).\n    /// @param self The host's schedule.\n    /// @param facilityId The full-width identifier, including zero.\n    /// @return scheduled Whether the identifier is present.\n    function contains(Heap storage self, uint256 facilityId) internal view returns (bool scheduled) {\n        scheduled = self.positions[facilityId] != 0;\n    }\n\n    /// @notice Returns the earliest event; equal deadlines prefer the smaller facility ID.\n    /// @dev Reverts with AccrualSchedule_Empty if empty. It does not check whether the event is due.\n    /// @param self The host's schedule.\n    /// @return next The minimum event, copied into memory without mutating storage.\n    function peek(Heap storage self) internal view returns (Event memory next) {\n        if (self.entries.length == 0) revert AccrualSchedule_Empty();\n        next = self.entries[0];\n    }\n\n    /// @notice Returns one facility's next event, in O(1).\n    /// @dev Reverts with AccrualSchedule_NotScheduled if the identifier is absent.\n    /// @param self The host's schedule.\n    /// @param facilityId The full-width identifier, including zero.\n    /// @return next The identified event, copied into memory.\n    function get(Heap storage self, uint256 facilityId) internal view returns (Event memory next) {\n        uint256 position = self.positions[facilityId];\n        if (position == 0) revert AccrualSchedule_NotScheduled(facilityId);\n        next = self.entries[position - 1];\n    }\n\n    /// @notice Inserts a facility's first next event, in O(log n).\n    /// @dev Duplicate IDs revert. The caller must validate authority, timing and servicing capacity.\n    /// @param self The host's schedule.\n    /// @param facilityId Full-width identifier; zero is permitted.\n    /// @param deadline Explicit timestamp; zero and uint64-max are permitted.\n    function insert(Heap storage self, uint256 facilityId, uint64 deadline) internal {\n        if (self.positions[facilityId] != 0) revert AccrualSchedule_AlreadyScheduled(facilityId);\n        uint256 index = self.entries.length;\n        self.entries.push(Event(facilityId, deadline));\n        self.positions[facilityId] = index + 1;\n        _siftUp(self, index);\n    }\n\n    /// @notice Replaces a present facility's deadline in either direction, in O(log n).\n    /// @dev A missing ID reverts. An identical deadline is an exact no-op. Moving backward in time\n    ///      is mechanically valid here; the host must enforce any contractual chronology policy.\n    /// @param self The host's schedule.\n    /// @param facilityId The existing full-width identifier.\n    /// @param deadline The replacement timestamp, including either uint64 endpoint.\n    /// @return previousDeadline The replaced value, allowing the host to emit its transition event.\n    function reschedule(Heap storage self, uint256 facilityId, uint64 deadline)\n        internal\n        returns (uint64 previousDeadline)\n    {\n        uint256 position = self.positions[facilityId];\n        if (position == 0) revert AccrualSchedule_NotScheduled(facilityId);\n        uint256 index = position - 1;\n        previousDeadline = self.entries[index].deadline;\n        if (deadline == previousDeadline) return previousDeadline;\n        self.entries[index].deadline = deadline;\n        if (deadline < previousDeadline) {\n            _siftUp(self, index);\n        } else {\n            _siftDown(self, index);\n        }\n    }\n\n    /// @notice Removes a particular facility's event in O(log n), leaving no position tombstone.\n    /// @dev A missing identifier reverts. The host decides who may cancel or retire an event.\n    /// @param self The host's schedule.\n    /// @param facilityId The full-width identifier to remove.\n    /// @return removed The old event, allowing the host to emit its transition event.\n    function remove(Heap storage self, uint256 facilityId) internal returns (Event memory removed) {\n        uint256 position = self.positions[facilityId];\n        if (position == 0) revert AccrualSchedule_NotScheduled(facilityId);\n        removed = _removeAt(self, position - 1);\n    }\n\n    /// @notice Removes and returns the earliest event in O(log n).\n    /// @dev Reverts if empty. The host must check due time and process the returned contractual\n    ///      event atomically; this data structure neither validates nor performs that processing.\n    /// @param self The host's schedule.\n    /// @return removed The minimum event, including its full-width facility ID.\n    function pop(Heap storage self) internal returns (Event memory removed) {\n        if (self.entries.length == 0) revert AccrualSchedule_Empty();\n        removed = _removeAt(self, 0);\n    }\n\n    /// @dev Removes a known valid index, fills its hole with the last entry, then repairs either\n    ///      upward or downward. No external call can observe the temporary relocation.\n    function _removeAt(Heap storage self, uint256 index) private returns (Event memory removed) {\n        removed = self.entries[index];\n        uint256 last = self.entries.length - 1;\n        if (index != last) {\n            Event memory replacement = self.entries[last];\n            self.entries[index] = replacement;\n            self.positions[replacement.facilityId] = index + 1;\n        }\n        self.entries.pop();\n        delete self.positions[removed.facilityId];\n        if (index < last) {\n            if (index != 0 && _less(self.entries[index], self.entries[(index - 1) / 2])) {\n                _siftUp(self, index);\n            } else {\n                _siftDown(self, index);\n            }\n        }\n    }\n\n    /// @dev Moves an entry upward until its parent is earlier or it becomes the root.\n    function _siftUp(Heap storage self, uint256 index) private {\n        while (index != 0) {\n            uint256 parent = (index - 1) / 2;\n            if (!_less(self.entries[index], self.entries[parent])) break;\n            _swap(self, index, parent);\n            index = parent;\n        }\n    }\n\n    /// @dev Visits only internal nodes. `index < size / 2` guarantees that 2*index+1 exists and\n    ///      that both child-index calculations fit uint256, without a narrowing capacity bound.\n    function _siftDown(Heap storage self, uint256 index) private {\n        uint256 size = self.entries.length;\n        while (index < size / 2) {\n            uint256 child = 2 * index + 1;\n            uint256 right = child + 1;\n            if (right < size && _less(self.entries[right], self.entries[child])) child = right;\n            if (!_less(self.entries[child], self.entries[index])) break;\n            _swap(self, index, child);\n            index = child;\n        }\n    }\n\n    /// @dev Swaps two distinct live entries and updates both reverse positions atomically.\n    function _swap(Heap storage self, uint256 first, uint256 second) private {\n        Event memory left = self.entries[first];\n        Event memory right = self.entries[second];\n        self.entries[first] = right;\n        self.entries[second] = left;\n        self.positions[right.facilityId] = first + 1;\n        self.positions[left.facilityId] = second + 1;\n    }\n\n    /// @dev Strict lexicographic order with no packed or narrowed facility identifier.\n    function _less(Event storage left, Event storage right) private view returns (bool) {\n        return left.deadline < right.deadline || (left.deadline == right.deadline && left.facilityId < right.facilityId);\n    }\n}\n"},{"file_path":"src/interfaces/ICollateralRegistry.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\n/// @title ICollateralRegistry\n/// @notice Per-vertical collateral-class parameters and book-level concentration\n///         accounting (ADR-0003 as amended: five classes at genesis, one of which is\n///         marked-to-market per ADR-0015).\ninterface ICollateralRegistry {\n    /// @notice How a class's collateral behaves — drives valuation and remedy paths.\n    enum CollateralModel {\n        Receivable, // legal-enforcement remedies (UCC foreclosure, secondary sale)\n        MarkedToMarket // margin-call / liquidation remedies (ADR-0015)\n\n    }\n\n    struct ClassParams {\n        string name;\n        CollateralModel model;\n        bool active;\n        uint16 maxLtvBps; // draw ceiling (initial LTV for MTM classes)\n        uint64 maxMaturity; // seconds from origination\n        uint16 concentrationLimitBps; // max share of total book in this class\n        // ── marked-to-market extension (zero for receivable classes) ──────\n        uint16 marginCallLtvBps; // breach → MarginCalled + cure window\n        uint16 liquidationLtvBps; // breach / cure expiry → LiquidationInitiated\n        uint64 maxMarkAge; // valuation freshness bound (seconds)\n    }\n\n    event ClassSet(uint256 indexed classId);\n    event ExposureRecorded(uint256 indexed classId, bytes32 indexed borrowerId, bytes32 indexed stateId, int256 delta);\n\n    /// @notice Emitted alongside `ExposureRecorded` when the increase came from PIK capitalisation\n    ///         rather than from an origination, so the two are distinguishable in the event stream.\n    /// @dev Origination exposure is a decision somebody made and an admission check passed.\n    ///      Capitalised exposure is arithmetic on a term already agreed. A reader reconciling the\n    ///      book needs to tell them apart, and `ExposureRecorded` alone cannot.\n    event CapitalizedExposureRecorded(\n        uint256 indexed classId, bytes32 indexed borrowerId, bytes32 indexed stateId, uint256 principal\n    );\n    event BorrowerLimitSet(uint16 limitBps);\n    /// @notice Governance set a per-borrower concentration limit overriding the global one.\n    /// @param borrowerId The borrower key.\n    /// @param limitBps The borrower's own max share of the book, in bps.\n    event BorrowerLimitOverrideSet(bytes32 indexed borrowerId, uint16 limitBps);\n    /// @notice Governance removed a per-borrower override; the global limit applies again.\n    /// @param borrowerId The borrower key.\n    event BorrowerLimitOverrideCleared(bytes32 indexed borrowerId);\n    event StateLimitSet(uint16 limitBps);\n    event ConcentrationFloorSet(uint256 floor);\n    /// @notice Governance changed the forward weight of an UNATTESTED past-due mark\n    ///         (OWNER DECISION 2026-08-07).\n    /// @param bps The new weight, in bps of the executable senior charge.\n    event PastDueWeightSet(uint256 bps);\n\n    /// @notice A class crossed FROM within its concentration limit TO above it\n    ///         (AUDIT FIX M-02). This is a book-shrink artefact: an amortising\n    ///         repayment, a default write-down, or the retirement of an unfunded\n    ///         facility removes exposure elsewhere, so an untouched class's SHARE of the\n    ///         remaining book rises without that class growing. Such a decrease can never\n    ///         be blocked (blocking it would let a concentration limit veto a loss being\n    ///         realized, inverting the loss cascade), so the breach is reported, not\n    ///         prevented — and no new exposure may be added to the class while it stands.\n    /// @param classId The class now above its limit.\n    /// @param exposure The class's exposure after the change (18-dec).\n    /// @param totalExposure The whole book's exposure after the change (18-dec).\n    /// @param limitBps The class's configured limit as a share of the book.\n    /// @param bookAboveFloor Whether the whole book is above the bootstrap floor. False\n    ///        means this is ordinary genesis concentration on a book too small for the\n    ///        relative limits to be the operative constraint (the absolute allowance\n    ///        `limitBps * floor / BPS` is); alerting should filter on this rather than\n    ///        treat a first facility at 100% of a tiny book as a risk incident.\n    event ConcentrationDrift(\n        uint256 indexed classId, uint256 exposure, uint256 totalExposure, uint16 limitBps, bool bookAboveFloor\n    );\n\n    /// @notice A class that was above its concentration limit is back within it — because\n    ///         the book grew around it or its own exposure fell (AUDIT FIX M-02).\n    /// @param classId The class now within its limit.\n    /// @param exposure The class's exposure after the change (18-dec).\n    /// @param totalExposure The whole book's exposure after the change (18-dec).\n    /// @param limitBps The class's configured limit as a share of the book.\n    /// @param bookAboveFloor Whether the whole book is above the bootstrap floor.\n    event ConcentrationHealed(\n        uint256 indexed classId, uint256 exposure, uint256 totalExposure, uint16 limitBps, bool bookAboveFloor\n    );\n\n    /// @notice A borrower crossed FROM within its concentration limit TO above it\n    ///         (AUDIT FIX M-02). Emitted for the borrower a write touches and for any id\n    ///         passed to `syncConcentrationBreaches`; the borrower key set is unbounded and\n    ///         not enumerable on-chain, but is fully recoverable from `ExposureRecorded`.\n    event BorrowerConcentrationDrift(\n        bytes32 indexed borrowerId, uint256 exposure, uint256 totalExposure, uint16 limitBps, bool bookAboveFloor\n    );\n\n    /// @notice A borrower that was above its concentration limit is back within it.\n    event BorrowerConcentrationHealed(\n        bytes32 indexed borrowerId, uint256 exposure, uint256 totalExposure, uint16 limitBps, bool bookAboveFloor\n    );\n\n    /// @notice A US state crossed FROM within its concentration limit TO above it.\n    event StateConcentrationDrift(\n        bytes32 indexed stateId, uint256 exposure, uint256 totalExposure, uint16 limitBps, bool bookAboveFloor\n    );\n\n    /// @notice A US state that was above its concentration limit is back within it.\n    event StateConcentrationHealed(\n        bytes32 indexed stateId, uint256 exposure, uint256 totalExposure, uint16 limitBps, bool bookAboveFloor\n    );\n\n    error Registry_UnknownClass(uint256 classId);\n    error Registry_ClassInactive(uint256 classId);\n    error Registry_BadParams();\n    /// @notice A configured class cannot change between receivable and marked-to-market\n    ///         accounting. The model selects materially different valuation and remedy\n    ///         paths and is fixed for the lifetime of a launch class.\n    error Registry_ModelImmutable(uint256 classId);\n    /// @notice The requested principal would push the book past the range in which the\n    ///         concentration arithmetic is provably overflow-free. Fails loudly with a\n    ///         decodable error rather than an arithmetic panic.\n    error Registry_PrincipalTooLarge();\n    /// @notice `setPastDueWeight` was asked for a weight of zero (which re-opens H-5/D5-03 by\n    ///         disabling the only permissionless senior protection on receivables) or a weight of\n    ///         `Config.BPS` or more (which restores the defect the weight exists to fix: an\n    ///         unattested mark carrying the same forward weight as an attested declared default).\n    ///         OWNER DECISION 2026-08-07. DO NOT DELETE EITHER BOUND.\n    /// @param bps The rejected weight.\n    error Registry_InvalidPastDueWeight(uint256 bps);\n    error Registry_ConcentrationExceeded(uint256 classId, uint256 wouldBe, uint256 limit);\n    error Registry_BorrowerConcentrationExceeded(bytes32 borrowerId, uint256 wouldBe, uint256 limit);\n    error Registry_StateConcentrationExceeded(bytes32 stateId, uint256 wouldBe, uint256 limit);\n    error Registry_ExposureUnderflow();\n\n    /// @notice Sets/updates a collateral class. Timelocked governance only.\n    /// @dev A class's collateral model is immutable after its first configuration.\n    function setClass(uint256 classId, ClassParams calldata p) external;\n\n    /// @notice Sets a per-borrower concentration limit overriding the global borrower limit.\n    function setBorrowerLimitOverride(bytes32 borrowerId, uint16 limitBps) external;\n\n    /// @notice Clears a per-borrower concentration limit override.\n    function clearBorrowerLimitOverride(bytes32 borrowerId) external;\n\n    /// @notice Class parameters (reverts for unknown classes).\n    function classParams(uint256 classId) external view returns (ClassParams memory);\n\n    /// @notice Reverts unless adding `principal` for (`classId`,`borrowerId`,`stateId`)\n    ///         respects every concentration limit (class, borrower, state). View-only;\n    ///         `recordExposure` performs the same checks at write time.\n    function checkConcentration(uint256 classId, bytes32 borrowerId, bytes32 stateId, uint256 principal)\n        external\n        view;\n\n    /// @notice Records an exposure increase (origination). Only CREDIT_ROLE (the\n    ///         collateral/credit layer). Enforces all concentration limits.\n    function recordExposureIncrease(uint256 classId, bytes32 borrowerId, bytes32 stateId, uint256 principal) external;\n\n    /// @notice Records an exposure increase that came from PIK interest CAPITALISATION rather than\n    ///         from an origination. Only CREDIT_ROLE. Books the exposure and reports every\n    ///         concentration breach exactly as the origination path does, but does NOT revert on\n    ///         one.\n    ///\n    /// @dev WHY THIS IS NOT A HOLE IN THE CONCENTRATION LIMIT, and why it is not optional.\n    ///      A concentration limit governs ADMISSION: it decides whether the book takes on a new\n    ///      risk somebody chose to take. Compounding interest is not that. Nobody elects it, the\n    ///      borrower cannot decline it, no capital moves, and the obligation was priced at\n    ///      origination when the limit was checked. Routing it through `recordExposureIncrease`\n    ///      meant a PIK book grew into its own limit with no adversary and then FROZE, and because\n    ///      `ClaimBridge.nextPaymentDue` only advances inside `WaterfallEngine.capitalizePik`, the\n    ///      freeze turned a borrower performing exactly as contracted into a permissionlessly\n    ///      markable past-due facility, and through `DefaultManager.pastDueExposure` into pending\n    ///      senior impairment. The protocol's own refusal became the credit event.\n    ///\n    ///      WHAT IS PRESERVED. The class must be known; the overflow bound that keeps the\n    ///      concentration arithmetic safe still applies; the exposure is booked in full, which is\n    ///      what keeps the facility WRITEABLE OFF (`realizeLoss` pairs its write-down with\n    ///      `recordExposureDecrease`, which reverts `Registry_ExposureUnderflow` if exposure lags);\n    ///      and every breach flag and drift event fires. Governance sees the limit crossed. The\n    ///      limit keeps its whole observation function and loses only its ability to brick a\n    ///      performing borrower.\n    ///\n    ///      `recordExposureDecrease` already carries this exact reasoning for the same reason:\n    ///      \"Reporting only - never a revert path.\"\n    ///\n    ///      WHAT THIS ADDS TO `CREDIT_ROLE`, stated because an auditor will ask. The role could\n    ///      already move exposure in both directions: `recordExposureIncrease` upward subject to\n    ///      the limits, and `recordExposureDecrease` downward with no check at all. This adds an\n    ///      upward path that skips the limit, so a CREDIT_ROLE holder can now inflate a class past\n    ///      its concentration ceiling. That moves NO VALUE - exposure is a reporting and\n    ///      write-off-accounting quantity, not a balance - and it moves the book in the\n    ///      CONSERVATIVE direction, making it read as more concentrated than it is. The role\n    ///      remains a protocol-modules-only grant for the reasons recorded on\n    ///      `recordExposureDecrease`, and this function does not change that requirement.\n    ///\n    ///      IF FOREST ROAD WANTS CAPITALISATION TO HARD-STOP AT THE LIMIT INSTEAD, that is a\n    ///      one-line change back to `recordExposureIncrease` in `WaterfallEngine.capitalizePik`,\n    ///      and it reinstates the denial of service knowingly rather than by accident.\n    function recordCapitalizedExposure(uint256 classId, bytes32 borrowerId, bytes32 stateId, uint256 principal)\n        external;\n\n    /// @notice Records an exposure decrease (repayment/writedown). Only CREDIT_ROLE.\n    function recordExposureDecrease(uint256 classId, bytes32 borrowerId, bytes32 stateId, uint256 principal) external;\n\n    /// @notice Current book exposure per class / borrower / state (18-dec).\n    function classExposure(uint256 classId) external view returns (uint256);\n    function borrowerExposure(bytes32 borrowerId) external view returns (uint256);\n    function stateExposure(bytes32 stateId) external view returns (uint256);\n    function totalBookExposure() external view returns (uint256);\n\n    /// @notice A class's current share of the whole book, in bps (0 on an empty book).\n    function classConcentrationBps(uint256 classId) external view returns (uint256);\n\n    /// @notice Whether a dimension's CURRENT share of the book exceeds its configured\n    ///         limit — the standing disclosure fact, floor-independent (AUDIT FIX M-02).\n    function isOverConcentrated(uint256 classId, bytes32 borrowerId, bytes32 stateId)\n        external\n        view\n        returns (bool classOver, bool borrowerOver, bool stateOver);\n\n    /// @notice The forward weight, in bps, that an UNATTESTED permissionless past-due mark\n    ///         (`DefaultManager.markPastDue`) carries in the conservative redemption NAV,\n    ///         relative to an ATTESTED declared default (OWNER DECISION 2026-08-07).\n    /// @dev Governed credit-risk policy, so it lives with the advance rates and concentration\n    ///      limits rather than in DefaultManager (which is EIP-170 constrained and contended).\n    ///      Never returns zero: an unset slot reads `Config.DEFAULT_PAST_DUE_WEIGHT_BPS`.\n    /// @return bps The effective weight, strictly between 0 and `Config.BPS`.\n    function pastDueWeightBps() external view returns (uint256 bps);\n\n    /// @notice Applies the governed unattested-past-due weight to an executable senior charge.\n    /// @dev Called by `DefaultManager.pendingSeniorImpairment` on the past-due cohort's charge\n    ///      AFTER the executable bound has been applied. Rounds UP (over-mark is the safe\n    ///      direction). OWNER DECISION 2026-08-07 — DO NOT turn this into a pass-through.\n    /// @param amount The executable senior charge attributable to the past-due cohort.\n    /// @return weighted The discounted charge that enters the conservative redemption NAV.\n    function weightedPastDueImpairment(uint256 amount) external view returns (uint256 weighted);\n\n    /// @notice The TOTAL conservative senior mark: the attested cohort at full weight plus the\n    ///         unattested past-due cohort, clamped to executable capacity and ramp-weighted.\n    /// @dev OWNER DECISION 2026-08-07. Clamps `pastDueSenior` to the senior absorption capacity\n    ///      `realizeLoss` could actually reach today (`vaultAssets` less the attested cohort's prior\n    ///      claim), THEN applies the governed weight, which itself ramps from\n    ///      `pastDueWeightBps()` back to `Config.BPS` over one `Config.DEFAULT_REDEEM_COOLDOWN`.\n    ///      Both the CLAMP-BEFORE-WEIGHT order and the ramp's expiry are load-bearing; see the\n    ///      implementation NatSpec.\n    /// @param pastDueSenior The past-due cohort's post-junior senior residual.\n    /// @param residual The TOTAL post-junior senior residual (both cohorts), unweighted.\n    /// @param vault The `sUSDfr` vault whose `totalAssets()` is layer 3's hard ceiling in\n    ///        `realizeLoss`. Read here rather than passed in as a number so the governed weight and\n    ///        the ceiling it is applied to stay in one timelocked module; see the implementation\n    ///        NatSpec, which also carries the recursion warning.\n    /// @param anchor `DefaultManager.pastDueReliefAnchor`. ZERO (unset) fails SAFE to full weight.\n    /// @return mark The total conservative senior impairment entering the redemption NAV.\n    function conservativeSeniorMark(uint256 pastDueSenior, uint256 residual, address vault, uint256 anchor)\n        external\n        view\n        returns (uint256 mark);\n\n    /// @notice The forward weight, in bps, an unattested past-due mark carries after `elapsed`\n    ///         seconds of its relief ramp (OWNER DECISION 2026-08-07).\n    /// @dev Ramps linearly from `pastDueWeightBps()` at `elapsed == 0` to `Config.BPS` at\n    ///      `elapsed >= Config.DEFAULT_REDEEM_COOLDOWN`, and stays at `Config.BPS` thereafter.\n    ///      A read-only convenience for operations and reference models; the mark itself does NOT\n    ///      route through it (see the implementation NatSpec for why).\n    /// @param elapsed Seconds since `DefaultManager.pastDueReliefAnchor`.\n    /// @return bps The effective weight, in `[pastDueWeightBps(), Config.BPS]`.\n    function pastDueRampWeightBps(uint256 elapsed) external view returns (uint256 bps);\n\n    /// @notice Governance sets the forward weight of an unattested past-due mark.\n    /// @dev Rejects 0 (re-opens H-5/D5-03) and `Config.BPS` or more (restores the defect).\n    /// @param bps The new weight, strictly between 0 and `Config.BPS`.\n    function setPastDueWeight(uint256 bps) external;\n\n    /// @notice Bitmap of classes currently above their limit; bit `classId - 1` set.\n    /// @dev Recomputed from the book on every call — never served from a cached slot, so it\n    ///      cannot report a clean book in the window after an implementation upgrade.\n    function overConcentratedClasses() external view returns (uint256 bitmap);\n\n    /// @notice The borrower concentration limit actually in force for `borrowerId`.\n    /// @dev The global limit assumes a vertical has many borrowers. A SINGLE-BORROWER vertical\n    ///      (Digital Assets, ADR-0015) makes the class and borrower dimensions measure the same\n    ///      exposure, so governance may set a per-borrower override. Every admission, breach\n    ///      and headroom read routes through this same number.\n    /// @param borrowerId The borrower key.\n    /// @return limitBps The effective limit in bps.\n    /// @return overridden True when a per-borrower override is set.\n    function effectiveBorrowerLimitBps(bytes32 borrowerId) external view returns (uint16 limitBps, bool overridden);\n\n    /// @notice Whether each supplied borrower currently holds more than the per-borrower limit\n    ///         as a share of the book — its OWN limit where one is overridden. The key set is\n    ///         unbounded on-chain; recover it from the `ExposureRecorded` stream and pass it in.\n    function overConcentratedBorrowers(bytes32[] calldata borrowerIds) external view returns (bool[] memory over);\n\n    /// @notice Whether each supplied state currently holds more than the per-state limit as\n    ///         a share of the book. Zero ids read false.\n    function overConcentratedStates(bytes32[] calldata stateIds) external view returns (bool[] memory over);\n\n    /// @notice Recomputes and events every concentration transition for all five classes\n    ///         plus the supplied borrower/state ids. Permissionless: it moves no value and\n    ///         only publishes facts the views already expose, so anyone (a keeper, a risk\n    ///         desk, the upgrade transaction itself) can announce a standing breach without\n    ///         waiting for the next origination or repayment.\n    function syncConcentrationBreaches(bytes32[] calldata borrowerIds, bytes32[] calldata stateIds) external;\n\n    /// @notice The largest `principal` that `checkConcentration` would admit right now for\n    ///         (`classId`,`borrowerId`,`stateId`) — the binding minimum across the class,\n    ///         borrower and state dimensions. Zero for an unknown or inactive class.\n    function concentrationHeadroom(uint256 classId, bytes32 borrowerId, bytes32 stateId)\n        external\n        view\n        returns (uint256);\n}\n"},{"file_path":"src/libraries/BridgeMixedInterestLib.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {IAttestationOracle} from \"../interfaces/IAttestationOracle.sol\";\nimport {ICollateralRegistry} from \"../interfaces/ICollateralRegistry.sol\";\nimport {IContinuousAccrual} from \"../interfaces/IContinuousAccrual.sol\";\nimport {IAccrualLifecycle} from \"../interfaces/IAccrualLifecycle.sol\";\nimport {IComplianceRegistry} from \"../interfaces/IComplianceRegistry.sol\";\n\n/// @title BridgeMixedInterestLib\n/// @notice Signed metadata and monotone cash/PIK clocks for one-facility mixed-interest notes.\n/// @dev Public methods execute by delegatecall in ClaimBridge's context. Authority, class checks,\n///      attestation consumption and reentrancy protection remain in ClaimBridge. This library owns\n///      an independent ERC-7201 namespace so no historical bridge field moves.\nlibrary BridgeMixedInterestLib {\n    bytes32 internal constant FEATURE_VERSION = keccak256(\"forestroad.mixed-interest.v1\");\n    bytes32 private constant ORIGINATION_DOMAIN = keccak256(\"forestroad.mixed-interest.origination.v1\");\n    bytes32 private constant AMENDMENT_DOMAIN = keccak256(\"forestroad.mixed-interest.amendment.v1\");\n\n    /// @notice The two authenticated rates and servicing clocks.\n    /// @dev LAYOUT-FROZEN: stored as a mapping value and embedded in PendingAmendment; changing\n    ///      its width or field order would shift live proxy storage.\n    struct InterestLegTerms {\n        uint16 cashRateBps;\n        uint16 pikRateBps;\n        uint64 cashPaymentInterval;\n        uint64 nextCashPaymentDue;\n        uint64 pikCapitalizationInterval;\n        uint64 nextPikCapitalization;\n    }\n\n    /// @dev ABI-identical mirror of ClaimBridge.OriginationTerms. Enums encode as uint8.\n    struct OriginationTerms {\n        uint256 classId;\n        bytes32 borrowerId;\n        bytes32 stateId;\n        uint256 principal;\n        uint16 ltvBps;\n        uint16 interestRateBps;\n        uint64 maturity;\n        address fundingRecipient;\n        uint64 paymentInterval;\n        uint64 nextPaymentDue;\n        uint8 rateType;\n        uint8 dayCountConvention;\n        bool renewable;\n        bytes32 paymentScheduleHash;\n        bytes32 rateIndexRef;\n        bytes32 renewalTermsHash;\n        bytes32 offchainRef;\n        bool pik;\n    }\n\n    /// @dev ABI-identical mirror of ClaimBridge.Amendment. Enums encode as uint8.\n    struct Amendment {\n        uint16 interestRateBps;\n        uint64 maturity;\n        uint64 paymentInterval;\n        uint64 nextPaymentDue;\n        uint8 rateType;\n        uint8 dayCountConvention;\n        bool renewable;\n        bytes32 paymentScheduleHash;\n        bytes32 rateIndexRef;\n        bytes32 renewalTermsHash;\n    }\n\n    /// @dev Storage-identical mirror of ClaimBridge.Facility. Enums encode in one byte.\n    struct Facility {\n        uint256 classId;\n        bytes32 borrowerId;\n        bytes32 stateId;\n        uint256 principal;\n        uint16 ltvBps;\n        uint16 interestRateBps;\n        uint64 maturity;\n        address fundingRecipient;\n        uint64 paymentInterval;\n        uint64 nextPaymentDue;\n        uint8 rateType;\n        uint8 dayCountConvention;\n        bool renewable;\n        bytes32 paymentScheduleHash;\n        bytes32 rateIndexRef;\n        bytes32 renewalTermsHash;\n        bytes32 offchainRef;\n        uint8 loanState;\n        bool pik;\n    }\n\n    /// @dev Storage-identical mirror of ClaimBridge.BridgeStorage.\n    struct BridgeStorage {\n        ICollateralRegistry registry;\n        IAttestationOracle oracle;\n        uint256 nextId;\n        mapping(uint256 tokenId => Facility) facilities;\n        mapping(uint256 classId => uint256) requiredMintAttestations;\n        address accrualReserve;\n    }\n\n    /// @custom:storage-location erc7201:forestroad.storage.ClaimBridgeMixedInterest\n    struct State {\n        mapping(uint256 facilityId => InterestLegTerms) terms;\n        mapping(uint256 facilityId => bytes32) commitment;\n        mapping(uint256 facilityId => bytes32) originationCommonHash;\n        mapping(uint256 facilityId => PendingAmendment) pendingAmendment;\n        bool enabled;\n        IComplianceRegistry borrowerPayoutRegistry;\n        // A cancelled preparation is rejected history, even when an originator later presents\n        // byte-identical terms at the still-current next id. The generation domain makes every\n        // post-cancellation commitment fresh, so the prior attester quorum cannot be replayed.\n        mapping(uint256 facilityId => uint256) originationGeneration;\n    }\n\n    struct PendingAmendment {\n        InterestLegTerms terms;\n        bytes32 commonHash;\n        bytes32 amendmentId;\n        bytes32 attestationHash;\n    }\n\n    bytes32 private constant MIXED_STORAGE_LOCATION = 0x5b29875874efdde9f2b0d1556dcca4e06c98ca7e47c1bf35a515d9037c1efb00;\n    bytes32 private constant BRIDGE_SLOT = 0xc9c2da543a2a10e4b712709fb6548fb2c0c97cecbac3457453966d18f1663f00;\n\n    uint8 private constant _ACTIVE = 1;\n    uint8 private constant _AMORTIZING = 2;\n    uint8 private constant _FIXED = 0;\n    uint8 private constant _ACTUAL_360 = 0;\n    uint8 private constant _THIRTY_360 = 2;\n    uint16 private constant _MAX_INTEREST_RATE_BPS = 10_000;\n\n    error MixedInterest_NotEnabled();\n    error MixedInterest_AlreadyEnabled();\n    error MixedInterest_InvalidTerms();\n    error MixedInterest_AlreadyConfigured(uint256 facilityId);\n    error MixedInterest_NotConfigured(uint256 facilityId);\n    /// @notice A signed one-shot amendment must be applied or revoked before staging its replacement.\n    error MixedInterest_UnconsumedAmendment(uint256 facilityId, bytes32 payload);\n    error Bridge_BadFacility();\n    error Bridge_UnknownToken(uint256 tokenId);\n    error Bridge_InvalidTransition(uint256 tokenId, uint8 from, uint8 to);\n    error Bridge_LegacyPikScheduleRequiresMigration(uint256 tokenId);\n    error Bridge_TermsAmendmentNotAttested(uint256 tokenId);\n    error Bridge_AccrualUnsupportedTerms(uint256 tokenId);\n    error Bridge_MixedInterestUnavailable();\n    error Bridge_AccrualReserveOnly(address caller);\n    error Bridge_AccrualDueManaged(uint256 tokenId);\n    error BorrowerPayout_RegistryAlreadySet(address registry);\n    error BorrowerPayout_InvalidRegistry(address registry);\n    error BorrowerPayout_RecipientNotAllowed(address recipient);\n\n    event BorrowerPayoutRegistrySet(address indexed registry);\n\n    event MixedInterestEnabled(bytes32 indexed version);\n    /// @notice Exact leg metadata staged for an origination (`actionId == 0`) or amendment.\n    /// @dev A later Originated/TermsAmended event carrying `termsHash` makes the staged record live;\n    ///      cancellation or replacement leaves it as rejected history. This keeps the mixed-leg\n    ///      register reconstructable from logs without trusting transaction calldata archives.\n    event MixedInterestTermsStaged(\n        uint256 indexed facilityId,\n        bytes32 indexed actionId,\n        bytes32 indexed termsHash,\n        uint16 cashRateBps,\n        uint16 pikRateBps,\n        uint64 cashPaymentInterval,\n        uint64 nextCashPaymentDue,\n        uint64 pikCapitalizationInterval,\n        uint64 nextPikCapitalization\n    );\n    event MixedInterestLegDueSet(uint256 indexed facilityId, uint8 indexed leg, uint64 previousDue, uint64 nextDue);\n    event NextPaymentDueSet(uint256 indexed tokenId, uint64 previousDue, uint64 nextDue);\n    event TermsAmended(uint256 indexed tokenId, bytes32 indexed amendmentId, bytes32 termsHash);\n\n    function enable() public {\n        State storage s = _state();\n        if (s.enabled) revert MixedInterest_AlreadyEnabled();\n        s.enabled = true;\n        emit MixedInterestEnabled(FEATURE_VERSION);\n    }\n\n    function enabled() public view returns (bool) {\n        return _state().enabled;\n    }\n\n    function bindBorrowerPayoutRegistry(address registry_) public returns (address bound) {\n        State storage s = _state();\n        address current = address(s.borrowerPayoutRegistry);\n        if (current != address(0)) revert BorrowerPayout_RegistryAlreadySet(current);\n        if (!_isBorrowerPayoutRegistry(registry_)) revert BorrowerPayout_InvalidRegistry(registry_);\n        s.borrowerPayoutRegistry = IComplianceRegistry(registry_);\n        emit BorrowerPayoutRegistrySet(registry_);\n        return registry_;\n    }\n\n    function borrowerPayoutRegistry() public view returns (address) {\n        return address(_state().borrowerPayoutRegistry);\n    }\n\n    function requireFundingRecipientAllowed(address recipient) public view returns (bool allowed) {\n        IComplianceRegistry policy = _state().borrowerPayoutRegistry;\n        if (address(policy) == address(0) || !policy.isFundingRecipientAllowed(recipient)) {\n            revert BorrowerPayout_RecipientNotAllowed(recipient);\n        }\n        return true;\n    }\n\n    function configured(uint256 id) public view returns (bool) {\n        return _state().terms[id].cashRateBps != 0;\n    }\n\n    function terms(uint256 id) public view returns (InterestLegTerms memory result) {\n        result = _state().terms[id];\n        if (result.cashRateBps == 0) revert MixedInterest_NotConfigured(id);\n    }\n\n    function commitment(uint256 id) public view returns (bytes32) {\n        return _state().commitment[id];\n    }\n\n    /// @notice Validates and stores a mixed origination before the host's safe-mint callback.\n    function stageOrigination(uint256 id, bytes calldata encoded) public returns (bytes32 termsHash) {\n        State storage s = _state();\n        if (!s.enabled) revert MixedInterest_NotEnabled();\n        if (s.terms[id].cashRateBps != 0) revert MixedInterest_AlreadyConfigured(id);\n        (OriginationTerms memory common, InterestLegTerms memory legs) =\n            abi.decode(encoded, (OriginationTerms, InterestLegTerms));\n        _validateOrigination(common, legs);\n        termsHash = _originationHash(s.originationGeneration[id], common, legs);\n        s.terms[id] = legs;\n        s.commitment[id] = termsHash;\n        s.originationCommonHash[id] = keccak256(abi.encode(common));\n        emit MixedInterestTermsStaged(\n            id,\n            bytes32(0),\n            termsHash,\n            legs.cashRateBps,\n            legs.pikRateBps,\n            legs.cashPaymentInterval,\n            legs.nextCashPaymentDue,\n            legs.pikCapitalizationInterval,\n            legs.nextPikCapitalization\n        );\n    }\n\n    /// @notice Confirms the ordinary origination calldata is the common half staged for this id.\n    function preparedOrigination(uint256 id, bytes calldata encodedCommon) public view returns (bytes32 termsHash) {\n        State storage s = _state();\n        termsHash = s.commitment[id];\n        if (\n            termsHash == bytes32(0) || s.originationCommonHash[id] == bytes32(0)\n                || s.originationCommonHash[id] != keccak256(encodedCommon)\n        ) revert MixedInterest_InvalidTerms();\n    }\n\n    function clearPreparedOrigination(uint256 id) public {\n        State storage s = _state();\n        if (s.originationCommonHash[id] == bytes32(0)) revert MixedInterest_NotConfigured(id);\n        delete s.terms[id];\n        delete s.commitment[id];\n        delete s.originationCommonHash[id];\n        ++s.originationGeneration[id];\n    }\n\n    /// @notice Validates and stages prospective mixed terms without changing the live clocks.\n    function stageAmendment(uint256 id, bytes32 amendmentId, bytes calldata encoded)\n        public\n        returns (bytes32 attestationHash)\n    {\n        State storage s = _state();\n        if (!s.enabled) revert MixedInterest_NotEnabled();\n        if (s.terms[id].cashRateBps == 0) revert MixedInterest_NotConfigured(id);\n        (bytes32 standing,, bool satisfied) =\n            _bridgeStorage().oracle.latestPayload(id, IAttestationOracle.AttestationKind.TermsAmended);\n        if (satisfied) revert MixedInterest_UnconsumedAmendment(id, standing);\n        (Amendment memory common, InterestLegTerms memory legs) = abi.decode(encoded, (Amendment, InterestLegTerms));\n        _validateAmendment(common, legs);\n        attestationHash = keccak256(abi.encode(AMENDMENT_DOMAIN, amendmentId, id, common, legs));\n        s.pendingAmendment[id] = PendingAmendment({\n            terms: legs,\n            commonHash: keccak256(abi.encode(common)),\n            amendmentId: amendmentId,\n            attestationHash: attestationHash\n        });\n        emit MixedInterestTermsStaged(\n            id,\n            amendmentId,\n            attestationHash,\n            legs.cashRateBps,\n            legs.pikRateBps,\n            legs.cashPaymentInterval,\n            legs.nextCashPaymentDue,\n            legs.pikCapitalizationInterval,\n            legs.nextPikCapitalization\n        );\n    }\n\n    /// @notice Applies either the historical one-leg amendment or a prepared two-leg amendment.\n    /// @dev The host supplies role, pause, reentrancy and source-freshness gates. This linked\n    ///      implementation preserves the original bridge namespace and emits from the proxy.\n    function amendTerms(uint256 id, bytes32 amendmentId, bytes calldata encoded) public {\n        Amendment memory a = abi.decode(encoded, (Amendment));\n        BridgeStorage storage bridge = _bridgeStorage();\n        if (id == 0 || id >= bridge.nextId) revert Bridge_UnknownToken(id);\n        Facility storage facility = bridge.facilities[id];\n        if (facility.loanState != _ACTIVE && facility.loanState != _AMORTIZING) revert Bridge_BadFacility();\n        bool mixed = _state().terms[id].cashRateBps != 0;\n        ICollateralRegistry.ClassParams memory classTerms = bridge.registry.classParams(facility.classId);\n        _validateCommonAmendment(facility, a, amendmentId, classTerms.maxMaturity, mixed);\n\n        bool continuous =\n            bridge.accrualReserve != address(0) && IContinuousAccrual(bridge.accrualReserve).accrualSnapshot().enabled;\n        if (continuous) _requireAccrualTerms(id, facility.pik, a.rateType, a.dayCountConvention);\n        if (\n            !continuous && facility.pik\n                && (a.paymentInterval != facility.paymentInterval || a.nextPaymentDue != facility.nextPaymentDue)\n        ) revert Bridge_LegacyPikScheduleRequiresMigration(id);\n\n        bytes32 expected;\n        InterestLegTerms memory legs;\n        if (mixed) (expected, legs) = _preparedAmendment(id, amendmentId, encoded);\n        else expected = keccak256(abi.encode(amendmentId, id, a));\n        (bytes32 payload,, bool ok) = bridge.oracle.latestPayload(id, IAttestationOracle.AttestationKind.TermsAmended);\n        if (!ok || payload != expected) revert Bridge_TermsAmendmentNotAttested(id);\n        bridge.oracle.consume(id, IAttestationOracle.AttestationKind.TermsAmended);\n\n        _checkpointAmendment(bridge.accrualReserve, id, amendmentId, a, continuous, mixed, legs);\n        _writeAmendment(facility, a);\n        emit TermsAmended(id, amendmentId, mixed ? expected : _creditTermsHash(facility));\n    }\n\n    /// @notice Hash for a facility's first preparation, before any cancellation history.\n    /// @dev After cancellation, use the hash returned by `stageOrigination`; its generation is\n    ///      deliberately private to the bridge so callers cannot mistake a stale preview for the\n    ///      commitment that attesters must sign.\n    function originationHash(bytes calldata encoded) public pure returns (bytes32 termsHash) {\n        (OriginationTerms memory common, InterestLegTerms memory legs) =\n            abi.decode(encoded, (OriginationTerms, InterestLegTerms));\n        return _originationHash(0, common, legs);\n    }\n\n    function amendmentHash(uint256 id, bytes32 amendmentId, bytes calldata encoded)\n        public\n        pure\n        returns (bytes32 termsHash)\n    {\n        (Amendment memory common, InterestLegTerms memory legs) = abi.decode(encoded, (Amendment, InterestLegTerms));\n        return keccak256(abi.encode(AMENDMENT_DOMAIN, amendmentId, id, common, legs));\n    }\n\n    /// @notice Advances the cash clock while preserving the aggregate earliest-due bridge field.\n    /// @dev The host supplies CREDIT_ROLE, reentrancy and source-idle gates.\n    function setCashDue(uint256 id, uint64 nextDue) public {\n        BridgeStorage storage bridge = _bridgeStorage();\n        Facility storage facility = _liveFacility(bridge, id);\n        if (facility.loanState != _ACTIVE && facility.loanState != _AMORTIZING) {\n            revert Bridge_InvalidTransition(id, facility.loanState, facility.loanState);\n        }\n        if (_state().terms[id].cashRateBps != 0) {\n            (uint64 previousAggregate, uint64 nextAggregate) = _setCashDue(id, facility.maturity, nextDue);\n            facility.nextPaymentDue = nextAggregate;\n            if (nextAggregate != previousAggregate) emit NextPaymentDueSet(id, previousAggregate, nextAggregate);\n            return;\n        }\n        if (\n            facility.pik && bridge.accrualReserve != address(0)\n                && IContinuousAccrual(bridge.accrualReserve).accrualSnapshot().enabled\n        ) revert Bridge_AccrualDueManaged(id);\n        uint64 previous = facility.nextPaymentDue;\n        if (nextDue <= previous || nextDue > facility.maturity) revert Bridge_BadFacility();\n        facility.nextPaymentDue = nextDue;\n        emit NextPaymentDueSet(id, previous, nextDue);\n    }\n\n    /// @notice Advances or completes the PIK clock from the permanently bound reserve only.\n    function setPikDue(uint256 id, uint64 nextDue) public {\n        BridgeStorage storage bridge = _bridgeStorage();\n        if (bridge.accrualReserve == address(0) || msg.sender != bridge.accrualReserve) {\n            revert Bridge_AccrualReserveOnly(msg.sender);\n        }\n        Facility storage facility = _liveFacility(bridge, id);\n        if (!facility.pik) revert Bridge_BadFacility();\n        if (facility.loanState != _ACTIVE && facility.loanState != _AMORTIZING) {\n            revert Bridge_InvalidTransition(id, facility.loanState, facility.loanState);\n        }\n        if (_state().terms[id].cashRateBps != 0) {\n            (uint64 previousAggregate, uint64 nextAggregate) = _setPikDue(id, facility.maturity, nextDue);\n            facility.nextPaymentDue = nextAggregate;\n            if (nextAggregate != previousAggregate) emit NextPaymentDueSet(id, previousAggregate, nextAggregate);\n            return;\n        }\n        uint64 previous = facility.nextPaymentDue;\n        if (nextDue <= previous || nextDue > facility.maturity) revert Bridge_BadFacility();\n        facility.nextPaymentDue = nextDue;\n        emit NextPaymentDueSet(id, previous, nextDue);\n    }\n\n    function _validateOrigination(OriginationTerms memory common, InterestLegTerms memory legs) private view {\n        if (\n            !common.pik || common.rateType != 0 || common.dayCountConvention != 0\n                || common.paymentInterval != legs.cashPaymentInterval\n                || common.nextPaymentDue != _aggregate(legs.nextCashPaymentDue, legs.nextPikCapitalization, common.maturity)\n        ) revert MixedInterest_InvalidTerms();\n        _validateLegs(common.interestRateBps, common.maturity, legs);\n    }\n\n    function _validateAmendment(Amendment memory common, InterestLegTerms memory legs) private view {\n        if (\n            common.rateType != 0 || common.dayCountConvention != 0 || common.paymentInterval != legs.cashPaymentInterval\n                || common.nextPaymentDue != _aggregate(legs.nextCashPaymentDue, legs.nextPikCapitalization, common.maturity)\n        ) revert MixedInterest_InvalidTerms();\n        _validateLegs(common.interestRateBps, common.maturity, legs);\n    }\n\n    function _validateLegs(uint16 totalRate, uint64 maturity, InterestLegTerms memory legs) private view {\n        if (\n            legs.cashRateBps == 0 || legs.pikRateBps == 0 || uint256(legs.cashRateBps) + legs.pikRateBps != totalRate\n                || totalRate > 10_000 || legs.cashPaymentInterval == 0 || legs.pikCapitalizationInterval == 0\n                || legs.nextCashPaymentDue <= block.timestamp || legs.nextCashPaymentDue > maturity\n                || legs.nextPikCapitalization <= block.timestamp || legs.nextPikCapitalization > maturity\n                || legs.cashPaymentInterval > legs.nextCashPaymentDue\n                || legs.pikCapitalizationInterval > legs.nextPikCapitalization\n        ) revert MixedInterest_InvalidTerms();\n    }\n\n    function _validateCommonAmendment(\n        Facility storage facility,\n        Amendment memory a,\n        bytes32 amendmentId,\n        uint64 maxMaturity,\n        bool mixed\n    ) private view {\n        if (\n            amendmentId == bytes32(0) || a.interestRateBps == 0 || a.interestRateBps > _MAX_INTEREST_RATE_BPS\n                || a.paymentInterval == 0 || a.nextPaymentDue <= block.timestamp || a.nextPaymentDue > a.maturity\n                || (!mixed && a.paymentInterval > a.nextPaymentDue) || a.maturity <= block.timestamp\n                || a.maturity > block.timestamp + maxMaturity || a.paymentScheduleHash == bytes32(0)\n                || (a.maturity > facility.maturity && !facility.renewable)\n                || (a.rateType == _FIXED) != (a.rateIndexRef == bytes32(0))\n                || a.renewable != (a.renewalTermsHash != bytes32(0))\n                || (facility.pik && (a.rateType != _FIXED || a.dayCountConvention != _ACTUAL_360))\n        ) revert Bridge_BadFacility();\n    }\n\n    function _checkpointAmendment(\n        address reserve,\n        uint256 id,\n        bytes32 amendmentId,\n        Amendment memory a,\n        bool continuous,\n        bool mixed,\n        InterestLegTerms memory legs\n    ) private {\n        if (mixed) {\n            if (!continuous) revert Bridge_MixedInterestUnavailable();\n            IAccrualLifecycle(reserve).amendMixedAccruingLoan(\n                id,\n                IAccrualLifecycle.MixedTerms({\n                    cashRateBps: legs.cashRateBps,\n                    pikRateBps: legs.pikRateBps,\n                    yearSeconds: uint32(360 days),\n                    nextPikCapitalization: legs.nextPikCapitalization,\n                    pikCapitalizationInterval: legs.pikCapitalizationInterval,\n                    maturity: a.maturity\n                })\n            );\n            _commitAmendment(id, amendmentId, abi.encode(a));\n        } else if (continuous) {\n            IAccrualLifecycle(reserve).amendAccruingLoan(\n                id,\n                IAccrualLifecycle.Terms({\n                    rateBps: a.interestRateBps,\n                    yearSeconds: a.dayCountConvention == _ACTUAL_360 ? uint32(360 days) : uint32(365 days),\n                    nextPaymentDue: a.nextPaymentDue,\n                    paymentInterval: a.paymentInterval,\n                    maturity: a.maturity\n                })\n            );\n        }\n    }\n\n    function _preparedAmendment(uint256 id, bytes32 amendmentId, bytes memory encodedCommon)\n        private\n        view\n        returns (bytes32 attestationHash, InterestLegTerms memory legs)\n    {\n        PendingAmendment storage pending = _state().pendingAmendment[id];\n        if (\n            pending.attestationHash == bytes32(0) || pending.amendmentId != amendmentId\n                || pending.commonHash != keccak256(encodedCommon)\n        ) revert MixedInterest_InvalidTerms();\n        return (pending.attestationHash, pending.terms);\n    }\n\n    function _commitAmendment(uint256 id, bytes32 amendmentId, bytes memory encodedCommon)\n        private\n        returns (InterestLegTerms memory legs)\n    {\n        State storage s = _state();\n        PendingAmendment storage pending = s.pendingAmendment[id];\n        if (\n            pending.attestationHash == bytes32(0) || pending.amendmentId != amendmentId\n                || pending.commonHash != keccak256(encodedCommon)\n        ) revert MixedInterest_InvalidTerms();\n        legs = pending.terms;\n        s.terms[id] = legs;\n        s.commitment[id] = pending.attestationHash;\n        delete s.pendingAmendment[id];\n    }\n\n    function _writeAmendment(Facility storage facility, Amendment memory a) private {\n        facility.interestRateBps = a.interestRateBps;\n        facility.maturity = a.maturity;\n        facility.paymentInterval = a.paymentInterval;\n        facility.nextPaymentDue = a.nextPaymentDue;\n        facility.rateType = a.rateType;\n        facility.dayCountConvention = a.dayCountConvention;\n        facility.renewable = a.renewable;\n        facility.paymentScheduleHash = a.paymentScheduleHash;\n        facility.rateIndexRef = a.rateIndexRef;\n        facility.renewalTermsHash = a.renewalTermsHash;\n    }\n\n    function _creditTermsHash(Facility storage f) private view returns (bytes32) {\n        OriginationTerms memory original = OriginationTerms({\n            classId: f.classId,\n            borrowerId: f.borrowerId,\n            stateId: f.stateId,\n            principal: f.principal,\n            ltvBps: f.ltvBps,\n            interestRateBps: f.interestRateBps,\n            maturity: f.maturity,\n            fundingRecipient: f.fundingRecipient,\n            paymentInterval: f.paymentInterval,\n            nextPaymentDue: f.nextPaymentDue,\n            rateType: f.rateType,\n            dayCountConvention: f.dayCountConvention,\n            renewable: f.renewable,\n            paymentScheduleHash: f.paymentScheduleHash,\n            rateIndexRef: f.rateIndexRef,\n            renewalTermsHash: f.renewalTermsHash,\n            offchainRef: f.offchainRef,\n            pik: f.pik\n        });\n        return keccak256(abi.encode(original));\n    }\n\n    function _requireAccrualTerms(uint256 id, bool pik, uint8 rateType, uint8 dayCount) private pure {\n        if (rateType != _FIXED || dayCount == _THIRTY_360 || (pik && dayCount != _ACTUAL_360)) {\n            revert Bridge_AccrualUnsupportedTerms(id);\n        }\n    }\n\n    function _aggregate(uint64 cashDue, uint64 pikDue, uint64 maturity) private pure returns (uint64) {\n        uint64 effectivePik = pikDue == 0 ? maturity : pikDue;\n        return cashDue < effectivePik ? cashDue : effectivePik;\n    }\n\n    function _originationHash(uint256 generation, OriginationTerms memory common, InterestLegTerms memory legs)\n        private\n        pure\n        returns (bytes32)\n    {\n        // Generation zero preserves the reviewed first-preparation commitment. Only a deliberate\n        // cancellation changes the domain, minimizing tooling churn while making that act durable.\n        if (generation == 0) return keccak256(abi.encode(ORIGINATION_DOMAIN, common, legs));\n        return keccak256(abi.encode(ORIGINATION_DOMAIN, generation, common, legs));\n    }\n\n    function _setCashDue(uint256 id, uint64 maturity, uint64 nextDue)\n        private\n        returns (uint64 previousAggregate, uint64 nextAggregate)\n    {\n        InterestLegTerms storage leg = _known(id);\n        uint64 previous = leg.nextCashPaymentDue;\n        // A bullet cash schedule can receive more than one partial payment after its cash clock\n        // has reached legal maturity. The aggregate bridge clock may still expose an earlier PIK\n        // boundary, so WaterfallEngine cannot identify this no-op from Facility.nextPaymentDue.\n        // Admit only the exact terminal repetition; every other cash-clock update stays strict.\n        if (nextDue == previous && nextDue == maturity) {\n            previousAggregate = _aggregate(previous, leg.nextPikCapitalization, maturity);\n            return (previousAggregate, previousAggregate);\n        }\n        if (nextDue <= previous || nextDue > maturity) revert MixedInterest_InvalidTerms();\n        previousAggregate = _aggregate(previous, leg.nextPikCapitalization, maturity);\n        leg.nextCashPaymentDue = nextDue;\n        nextAggregate = _aggregate(nextDue, leg.nextPikCapitalization, maturity);\n        emit MixedInterestLegDueSet(id, 0, previous, nextDue);\n    }\n\n    function _setPikDue(uint256 id, uint64 maturity, uint64 nextDue)\n        private\n        returns (uint64 previousAggregate, uint64 nextAggregate)\n    {\n        InterestLegTerms storage leg = _known(id);\n        uint64 previous = leg.nextPikCapitalization;\n        if (previous == 0 || (nextDue != 0 && (nextDue <= previous || nextDue > maturity))) {\n            revert MixedInterest_InvalidTerms();\n        }\n        previousAggregate = _aggregate(leg.nextCashPaymentDue, previous, maturity);\n        leg.nextPikCapitalization = nextDue;\n        nextAggregate = _aggregate(leg.nextCashPaymentDue, nextDue, maturity);\n        emit MixedInterestLegDueSet(id, 1, previous, nextDue);\n    }\n\n    function _liveFacility(BridgeStorage storage bridge, uint256 id) private view returns (Facility storage facility) {\n        if (id == 0 || id >= bridge.nextId) revert Bridge_UnknownToken(id);\n        return bridge.facilities[id];\n    }\n\n    function _known(uint256 id) private view returns (InterestLegTerms storage leg) {\n        leg = _state().terms[id];\n        if (leg.cashRateBps == 0) revert MixedInterest_NotConfigured(id);\n    }\n\n    function _state() private pure returns (State storage $) {\n        assembly {\n            $.slot := MIXED_STORAGE_LOCATION\n        }\n    }\n\n    function _isBorrowerPayoutRegistry(address registry_) private view returns (bool valid) {\n        if (registry_.code.length == 0) return false;\n        (bool ok, bytes memory data) =\n            registry_.staticcall(abi.encodeCall(IComplianceRegistry.isFundingRecipientAllowed, (address(0))));\n        if (!ok || data.length != 32) return false;\n        uint256 word;\n        assembly (\"memory-safe\") {\n            word := mload(add(data, 0x20))\n        }\n        return word <= 1;\n    }\n\n    function _bridgeStorage() private pure returns (BridgeStorage storage bridge) {\n        assembly {\n            bridge.slot := BRIDGE_SLOT\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/Panic.sol","source_code":"// 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"},{"file_path":"src/ClaimBridge.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {AccessControlUpgradeable} from \"@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol\";\nimport {Initializable} from \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport {UUPSUpgradeable} from \"@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol\";\nimport {ERC721Upgradeable} from \"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol\";\nimport {PausableUpgradeable} from \"@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol\";\nimport {ReentrancyGuardUpgradeable} from \"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol\";\n\nimport {IAttestationOracle} from \"./interfaces/IAttestationOracle.sol\";\nimport {ICollateralRegistry} from \"./interfaces/ICollateralRegistry.sol\";\nimport {Config} from \"./libraries/Config.sol\";\nimport {LossEventIds} from \"./libraries/LossEventIds.sol\";\nimport {Roles} from \"./libraries/Roles.sol\";\nimport {IContinuousAccrual} from \"./interfaces/IContinuousAccrual.sol\";\nimport {IAccrualExposure} from \"./interfaces/IAccrualExposure.sol\";\nimport {IAccrualBridge} from \"./interfaces/IAccrualLifecycle.sol\";\nimport {BridgeAccrualLib} from \"./libraries/BridgeAccrualLib.sol\";\nimport {BridgeMixedInterestLib} from \"./libraries/BridgeMixedInterestLib.sol\";\n\n/// @title ClaimBridge - tokenized facility positions (the CALIBER analog, ADR-0006)\n/// @notice Each ERC-721 token is the on-chain position of record for one identified,\n///         lien-perfected facility. THE SYNCHRONIZED MINT GATE (CLAUDE.md section 1.3): a\n///         facility cannot mint unless every attestation kind required for its class is\n///         currently satisfied, and the deal-identity attestations (`AssignmentExecuted`,\n///         `UCCFiled` and `CreditIssued`) commit to EXACTLY the terms being minted (AUDIT\n///         FIX H-4 / P-32 - full payload binding; `Valuation` retains its mark payload), AND all on-chain\n///         conditions hold (class active, LTV and maturity within class parameters, every\n///         concentration limit respected - checked atomically through the registry).\n///         Attestations that merely EXIST at a facility id are not sufficient: they must\n///         attest to this obligor, this class, this amount, this tenor and this lien.\n///         Escrow release is contractually\n///         conditioned off-chain on the existence of this token (legal wrapper section 3).\n///\n///         Positions are transfer-restricted: facilities are held by protocol/SPV\n///         custody addresses; transfers require governance execution, and DEFAULTED or\n///         ACCELERATED positions are frozen entirely.\ncontract ClaimBridge is\n    Initializable,\n    ERC721Upgradeable,\n    PausableUpgradeable,\n    ReentrancyGuardUpgradeable,\n    AccessControlUpgradeable,\n    UUPSUpgradeable,\n    IAccrualBridge\n{\n    enum RateType {\n        Fixed,\n        Variable\n    }\n\n    enum DayCountConvention {\n        Actual360,\n        Actual365,\n        Thirty360\n    }\n\n    enum LoanState {\n        Pending, // minted, awaiting funding\n        Active, // funded, performing\n        Amortizing, // in scheduled repayment\n        Repaid, // closed, made whole\n        Defaulted, // default declared - token frozen\n        Accelerated, // waterfall shifted to acceleration - token frozen\n        Cancelled, // AUDIT FIX (M-02): pending facility retired before funding - NFT burned\n        Resolved // AUDIT FIX (M-03): defaulted facility worked out to full principal recovery\n\n    }\n\n    struct Facility {\n        uint256 classId;\n        bytes32 borrowerId; // stable pseudonymous borrower key (off-chain KYB record)\n        bytes32 stateId; // US state key for tax-credit classes (zero elsewhere)\n        uint256 principal; // 18-dec\n        uint16 ltvBps;\n        // Contractual annual rate for THIS facility, supplied and signed per facility.\n        uint16 interestRateBps;\n        uint64 maturity; // absolute timestamp\n        address fundingRecipient; // attested destination; the servicer cannot redirect funding\n        uint64 paymentInterval; // contractual seconds between scheduled payments\n        uint64 nextPaymentDue; // absolute due date used by permissionless past-due marking\n        RateType rateType;\n        DayCountConvention dayCountConvention;\n        bool renewable;\n        bytes32 paymentScheduleHash; // full amortization schedule\n        bytes32 rateIndexRef; // required for variable-rate facilities\n        bytes32 renewalTermsHash; // required when renewable\n        bytes32 offchainRef; // UCC filing / SPV-series / escrow reference hash\n        LoanState state;\n        /// @notice Whether this facility contractually CAPITALISES unpaid interest (PIK).\n        /// @dev TAIL-APPENDED 2026-09-08. Set once at origination and never amended: `Amendment`\n        ///      deliberately does not carry it, so a cash-pay facility can never be converted into a\n        ///      capitalising one by a later signature. Converting the other way would also be a\n        ///      restructuring, and a restructuring should be a new facility rather than a flag flip.\n        ///\n        ///      IT IS IN THE TERMS HASH, so it is signed by the `CreditIssued` quorum along with the\n        ///      rate. Without it `WaterfallEngine.capitalizePik` had nothing to distinguish a PIK\n        ///      facility from an ordinary cash-pay one, and any address could force PIK accounting\n        ///      onto the cash-pay book: the interest was capitalised into `deployed` AND then paid\n        ///      again in cash through `distribute`, leaving a phantom receivable that only a real\n        ///      charge against curator first-loss could ever clear.\n        bool pik;\n    }\n\n    struct OriginationTerms {\n        uint256 classId;\n        bytes32 borrowerId;\n        bytes32 stateId;\n        uint256 principal;\n        uint16 ltvBps;\n        uint16 interestRateBps;\n        uint64 maturity;\n        address fundingRecipient;\n        uint64 paymentInterval;\n        uint64 nextPaymentDue;\n        RateType rateType;\n        DayCountConvention dayCountConvention;\n        bool renewable;\n        bytes32 paymentScheduleHash;\n        bytes32 rateIndexRef;\n        bytes32 renewalTermsHash;\n        bytes32 offchainRef;\n        /// @notice Whether this facility contractually capitalises unpaid interest. Signed.\n        bool pik;\n    }\n\n    struct Amendment {\n        uint16 interestRateBps;\n        uint64 maturity;\n        uint64 paymentInterval;\n        uint64 nextPaymentDue;\n        RateType rateType;\n        DayCountConvention dayCountConvention;\n        bool renewable;\n        bytes32 paymentScheduleHash;\n        bytes32 rateIndexRef;\n        bytes32 renewalTermsHash;\n    }\n\n    /// @custom:storage-location erc7201:forestroad.storage.ClaimBridge\n    struct BridgeStorage {\n        ICollateralRegistry registry;\n        IAttestationOracle oracle;\n        uint256 nextId;\n        mapping(uint256 tokenId => Facility) facilities;\n        // per-class required attestation kinds for minting (bitmask over\n        // IAttestationOracle.AttestationKind)\n        mapping(uint256 classId => uint256) requiredMintAttestations;\n        // Permanent continuous source, appended after all historical bridge fields.\n        address accrualReserve;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"forestroad.storage.ClaimBridge\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant BRIDGE_STORAGE_LOCATION =\n        0xc9c2da543a2a10e4b712709fb6548fb2c0c97cecbac3457453966d18f1663f00;\n\n    /// @dev AUDIT FIX (section 3.1 reconstructability): carries the full originated terms so\n    ///      the register - including WHEN principal is due (`maturity`) and WHICH\n    ///      perfected lien backs it (`offchainRef`) - is reconstructable purely from\n    ///      events, not only from the mutable `facility()` view.\n    event Originated(uint256 indexed tokenId, uint256 indexed classId, bytes32 indexed borrowerId, bytes32 termsHash);\n    event NextPaymentDueSet(uint256 indexed tokenId, uint64 previousDue, uint64 nextDue);\n    event TermsAmended(uint256 indexed tokenId, bytes32 indexed amendmentId, bytes32 termsHash);\n    event StateChanged(uint256 indexed tokenId, LoanState from, LoanState to);\n    event RequiredAttestationsSet(uint256 indexed classId, uint256 kindsMask);\n    /// @notice Governance permanently bound this bridge's authenticated accrual source.\n    event AccrualReserveSet(address indexed reserve);\n    /// @notice Governance permanently bound the borrower-payout policy used at origination.\n    event BorrowerPayoutRegistrySet(address indexed registry);\n    event MixedInterestOriginationPrepared(uint256 indexed tokenId, bytes32 indexed termsHash);\n    /// @notice Exact staged cash/PIK metadata; activated only by a later matching origination or amendment log.\n    event MixedInterestTermsStaged(\n        uint256 indexed facilityId,\n        bytes32 indexed actionId,\n        bytes32 indexed termsHash,\n        uint16 cashRateBps,\n        uint16 pikRateBps,\n        uint64 cashPaymentInterval,\n        uint64 nextCashPaymentDue,\n        uint64 pikCapitalizationInterval,\n        uint64 nextPikCapitalization\n    );\n    event MixedInterestOriginationCancelled(uint256 indexed tokenId);\n    event MixedInterestAmendmentPrepared(\n        uint256 indexed tokenId, bytes32 indexed amendmentId, bytes32 indexed termsHash\n    );\n\n    /// @dev Number of `IAttestationOracle.AttestationKind` values. The mint-gate setter and the\n    ///      `originate` gate loop BOTH derive from this, so a future kind cannot be accepted by\n    ///      governance while remaining unread by the gate (PM-R-09).\n    uint256 private constant KIND_COUNT = 9;\n    /// @dev Every valid attestation-kind bit set.\n    uint256 private constant KINDS_MASK_ALL = (1 << KIND_COUNT) - 1;\n    /// @dev AUDIT FIX (H-4): the `CreditIssued` bit. This kind is the TERMS attestation -\n    ///      the 2-of-n quorum that authorizes an amount for a counterparty - so it is\n    ///      mandatory in every class's mint gate and its payload is bound in `originate`.\n    uint256 private constant BIT_CREDIT_ISSUED = 1 << uint256(uint8(IAttestationOracle.AttestationKind.CreditIssued));\n\n    error Bridge_ZeroAddress();\n    /// @notice A mint-gate mask carried bits outside the known `AttestationKind` range, or was\n    ///         empty. Either would leave the gate weaker than it reads (PM-R-09).\n    /// @param kindsMask The rejected mask.\n    error Bridge_BadAttestationMask(uint256 kindsMask);\n    error Bridge_BadFacility();\n    /// @notice Legacy PIK coupon dates can change only after migration to the native lifecycle.\n    error Bridge_LegacyPikScheduleRequiresMigration(uint256 tokenId);\n    error Bridge_AttestationMissing(uint256 classId, IAttestationOracle.AttestationKind kind);\n    /// @notice AUDIT FIX (H-4): the currently-satisfied `CreditIssued` attestation at this\n    ///         facility id does not commit to THESE terms. Either no terms were attested, or\n    ///         the attested terms describe a different obligor/class/amount/tenor/lien.\n    /// @param facilityId The facility id the gate read.\n    /// @param expected The terms hash of the facility being originated/funded.\n    /// @param attested The terms hash actually carried by the attestation (zero if none).\n    error Bridge_TermsNotAttested(uint256 facilityId, bytes32 expected, bytes32 attested);\n    /// @notice A deal-identity attestation is present but commits to different terms.\n    /// @param classId The collateral class whose mint gate failed.\n    /// @param kind The deal-identity attestation kind.\n    /// @param expected The terms hash of the facility being originated/funded.\n    /// @param attested The terms hash carried by the attestation.\n    error Bridge_AttestationNotBoundToDeal(\n        uint256 classId, IAttestationOracle.AttestationKind kind, bytes32 expected, bytes32 attested\n    );\n    error Bridge_ValuationStale(uint256 tokenIdOrZero, uint64 asOf, uint64 maxAge);\n    error Bridge_LtvExceedsValue(uint256 principal, uint256 maxByValue);\n    error Bridge_InvalidTransition(uint256 tokenId, LoanState from, LoanState to);\n    error Bridge_PositionFrozen(uint256 tokenId);\n    error Bridge_TransferRestricted();\n    error Bridge_UnknownToken(uint256 tokenId);\n    error Bridge_FacilityMatured(uint256 tokenId);\n    error Bridge_ClassInactive(uint256 classId);\n    error Bridge_NotPending(uint256 tokenId);\n    error Bridge_TermsAmendmentNotAttested(uint256 tokenId);\n    error Bridge_FacilityEventNamespaceExhausted(uint256 nextId);\n    /// @notice The continuous accounting source cannot be replaced after binding.\n    error Bridge_AccrualAlreadyBound();\n    /// @notice Only the bound source can advance its signed PIK capitalization schedule.\n    error Bridge_AccrualReserveOnly(address caller);\n    /// @notice A live continuous facility must use the supported fixed-rate day-count scope.\n    error Bridge_AccrualUnsupportedTerms(uint256 tokenId);\n    /// @notice A continuous PIK schedule advances only through its accounting source or signed amendment.\n    error Bridge_AccrualDueManaged(uint256 tokenId);\n    /// @notice A mixed facility must retain both legs through its dedicated lifecycle entry point.\n    error Bridge_MixedLifecycleRequired(uint256 tokenId);\n    /// @notice Activation requires the enabled, fresh and version-matched continuous system.\n    error Bridge_MixedInterestUnavailable();\n\n    uint16 public constant MAX_INTEREST_RATE_BPS = 10_000;\n    bytes32 private constant _MIXED_INTEREST_VERSION = keccak256(\"forestroad.mixed-interest.v1\");\n\n    /// @custom:oz-upgrades-unsafe-allow constructor\n    constructor() {\n        _disableInitializers();\n    }\n\n    /// @notice Initializes the position register.\n    /// @param admin Governance timelock.\n    /// @param guardian Emergency pauser.\n    /// @param upgrader Upgrade authority (timelock).\n    /// @param registry The collateral registry (class params + concentration).\n    /// @param oracle The attestation oracle (mint gate; ADR-0007 trust note applies).\n    function initialize(address admin, address guardian, address upgrader, address registry, address oracle)\n        external\n        initializer\n    {\n        if (\n            admin == address(0) || guardian == address(0) || upgrader == address(0) || registry == address(0)\n                || oracle == address(0)\n        ) revert Bridge_ZeroAddress();\n        __ERC721_init(\"Forest Road Facility\", \"frFACILITY\");\n        __Pausable_init();\n        __ReentrancyGuard_init();\n        __AccessControl_init();\n        __UUPSUpgradeable_init();\n        _grantRole(DEFAULT_ADMIN_ROLE, admin);\n        _grantRole(Roles.GUARDIAN_ROLE, guardian);\n        _grantRole(Roles.UPGRADER_ROLE, upgrader);\n        BridgeStorage storage $ = _storage();\n        $.registry = ICollateralRegistry(registry);\n        $.oracle = IAttestationOracle(oracle);\n        $.nextId = 1;\n    }\n\n    // -- governance -------------------------------------------------------\n\n    /// @notice Permanently binds the reserve after the underlying token has bound that same source.\n    /// @param reserve The already configured reserve proxy for this bridge's native module routes.\n    function setAccrualReserve(address reserve) external onlyRole(DEFAULT_ADMIN_ROLE) {\n        BridgeStorage storage $ = _storage();\n        if ($.accrualReserve != address(0)) revert Bridge_AccrualAlreadyBound();\n        BridgeAccrualLib.validate(reserve, address($.registry), address($.oracle));\n        IAccrualExposure(reserve).requireAccrualIdle();\n        $.accrualReserve = reserve;\n        emit AccrualReserveSet(reserve);\n    }\n\n    /// @notice The permanent accounting source, or zero before continuous accrual is bound.\n    function accrualReserve() external view returns (address) {\n        return _storage().accrualReserve;\n    }\n\n    /// @notice Permanently binds the timelock-managed borrower-payout registry.\n    function setBorrowerPayoutRegistry(address registry) external onlyRole(DEFAULT_ADMIN_ROLE) {\n        // The library returns the bound address only to keep the delegatecall compact. Binding\n        // either validates, stores and emits, or reverts; the host has no second value to check.\n        BridgeMixedInterestLib.bindBorrowerPayoutRegistry(registry);\n    }\n\n    /// @notice Irreversibly enables new mixed facilities after every accounting module matches.\n    function enableMixedInterest() external onlyRole(DEFAULT_ADMIN_ROLE) {\n        BridgeStorage storage $ = _storage();\n        address reserve = $.accrualReserve;\n        if (reserve == address(0) || !IContinuousAccrual(reserve).accrualSnapshot().enabled) {\n            revert Bridge_MixedInterestUnavailable();\n        }\n        IContinuousAccrual(reserve).requireAccrualFresh();\n        IAccrualExposure(reserve).requireAccrualIdle();\n        BridgeAccrualLib.activateMixed(reserve);\n        BridgeMixedInterestLib.enable();\n    }\n\n    /// @notice Exact cross-module version used by activation and downgrade checks.\n    function mixedInterestVersion() external pure returns (bytes32) {\n        return _MIXED_INTEREST_VERSION;\n    }\n\n    function mixedInterestEnabled() external view returns (bool) {\n        return BridgeMixedInterestLib.enabled();\n    }\n\n    /// @notice Stages the current next id's encoded common and leg terms for attester review.\n    /// @dev `encoded` is `abi.encode(OriginationTerms, InterestLegTerms)`. No facility or exposure\n    ///      exists until the ordinary `originate` call presents the exact common terms.\n    function prepareMixedOrigination(bytes calldata encoded)\n        external\n        onlyRole(Roles.ORIGINATOR_ROLE)\n        whenNotPaused\n        nonReentrant\n        returns (uint256 tokenId, bytes32 termsHash)\n    {\n        _requireAccrualFresh();\n        tokenId = _storage().nextId;\n        termsHash = BridgeMixedInterestLib.stageOrigination(tokenId, encoded);\n        emit MixedInterestOriginationPrepared(tokenId, termsHash);\n    }\n\n    function cancelPreparedMixedOrigination() external onlyRole(Roles.ORIGINATOR_ROLE) nonReentrant {\n        _requireAccrualIdle();\n        uint256 tokenId = _storage().nextId;\n        BridgeMixedInterestLib.clearPreparedOrigination(tokenId);\n        emit MixedInterestOriginationCancelled(tokenId);\n    }\n\n    /// @notice Stages both prospective leg schedules for exact attester review.\n    /// @dev `encoded` is `abi.encode(Amendment, InterestLegTerms)`. Staging alone does not\n    ///      checkpoint, amend or otherwise change a live facility.\n    function prepareMixedAmendment(uint256 tokenId, bytes32 amendmentId, bytes calldata encoded)\n        external\n        onlyRole(Roles.ORIGINATOR_ROLE)\n        whenNotPaused\n        nonReentrant\n        returns (bytes32 termsHash)\n    {\n        _requireAccrualFresh();\n        Facility storage f = _facility(_storage(), tokenId);\n        if (!BridgeMixedInterestLib.configured(tokenId)) revert Bridge_MixedLifecycleRequired(tokenId);\n        if (f.state != LoanState.Active && f.state != LoanState.Amortizing) revert Bridge_BadFacility();\n        if (amendmentId == bytes32(0)) revert Bridge_BadFacility();\n        termsHash = BridgeMixedInterestLib.stageAmendment(tokenId, amendmentId, encoded);\n        emit MixedInterestAmendmentPrepared(tokenId, amendmentId, termsHash);\n    }\n\n    /// @notice Sets the attestation kinds required to mint a facility of `classId`\n    ///         (bitmask over AttestationKind). Timelocked governance only.\n    /// @dev AUDIT FIX (PM-R-09). Previously ANY `uint256` was stored, while `originate` only ever\n    ///      reads bits `0..KIND_COUNT-1`. A mask carrying a high bit therefore READ stricter than\n    ///      it behaved - the silent fail-open class this protocol has been bitten by before. Two\n    ///      rejections now, both fail-loud:\n    ///        - bits outside the known `AttestationKind` range: a governance typo can no longer\n    ///          silently widen the mint gate;\n    ///        - an EMPTY mask: a zero gate makes the section 1.3 \"NFT mint gate\" invariant vacuous for\n    ///          that class (a facility could mint with NO attested off-chain fact at all).\n    ///          `Validate.s.sol` already asserts every class's gate is non-zero; this makes the\n    ///          contract enforce what validation merely checked after the fact.\n    ///\n    ///      AUDIT FIX (H-4): a mask omitting `CreditIssued` is now rejected as well. `originate`\n    ///      binds the facility's TERMS to the `CreditIssued` payload unconditionally, so a class\n    ///      whose declared gate omitted that bit would read weaker than it behaves - and, before\n    ///      the binding existed, such a class (the digital-assets class) had NO attested amount\n    ///      or counterparty at all.\n    /// @param classId The collateral class.\n    /// @param kindsMask Bitmask over `AttestationKind`; must be within `KINDS_MASK_ALL` and\n    ///        must include the `CreditIssued` bit.\n    function setRequiredMintAttestations(uint256 classId, uint256 kindsMask) external onlyRole(DEFAULT_ADMIN_ROLE) {\n        _requireAccrualIdle();\n        if (kindsMask & ~KINDS_MASK_ALL != 0 || kindsMask & BIT_CREDIT_ISSUED == 0) {\n            revert Bridge_BadAttestationMask(kindsMask);\n        }\n        _storage().requiredMintAttestations[classId] = kindsMask;\n        emit RequiredAttestationsSet(classId, kindsMask);\n    }\n\n    // -- origination (THE synchronized mint gate) -------------------------\n\n    /// @notice Mints the position NFT for an underwritten facility - ONLY if every\n    ///         off-chain condition (required attestations, with every deal-identity quorum\n    ///         committing to EXACTLY these terms) AND on-chain condition (class params,\n    ///         LTV, maturity, concentration) holds. Escrow releases off-chain only after\n    ///         this token exists.\n    /// @dev AUDIT FIX (H-4) - FULL PAYLOAD BINDING. The gate previously proved only that\n    ///      attestations EXISTED at the facility id it was about to mint; it never proved\n    ///      they attested to the facility's TERMS. Two consequences, both measured:\n    ///        - SEQUENCE DESYNC: `nextId` only advances on a SUCCESSFUL mint, so a reverted\n    ///          or reordered origination left a fully-attested bundle sitting at the id the\n    ///          next call would read. A completely unattested borrower could then originate\n    ///          against another obligor's attestations (and, for a marked-to-market class,\n    ///          against another obligor's appraisal).\n    ///        - UNBOUNDED PRINCIPAL: for the four Receivable classes nothing on-chain bound\n    ///          the amount at all - `ltvBps <= maxLtvBps` is a ratio with no denominator -\n    ///          so a bundle diligenced for a $500k receivable could mint any principal.\n    ///      Both close by requiring the deal-identity payloads to equal\n    ///      `creditTermsHash(...)` over the exact terms being minted. `Valuation` is excluded\n    ///      because its payload is the mark. This reuses the\n    ///      `latestPayload` primitive already used by the attestation consumers. Note the attested principal IS the on-chain principal bound:\n    ///      the amount is now a signed term, not an originator-chosen input, so the LTV\n    ///      ratio's denominator (`principal * BPS / ltvBps`) is attested too.\n    /// @param holder Custody address for the position (SPV series custodian).\n    /// @param terms Complete contractual and operational facility terms.\n    /// @return tokenId The minted facility id.\n    function originate(address holder, OriginationTerms calldata terms)\n        external\n        onlyRole(Roles.ORIGINATOR_ROLE)\n        whenNotPaused\n        nonReentrant\n        returns (uint256 tokenId)\n    {\n        _requireAccrualFresh();\n        Facility memory f = _facilityFrom(terms);\n        BridgeStorage storage $ = _storage();\n        bytes32 termsHash = BridgeMixedInterestLib.commitment($.nextId);\n        if (termsHash == bytes32(0)) termsHash = _creditTermsHash(f);\n        else termsHash = BridgeMixedInterestLib.preparedOrigination($.nextId, abi.encode(terms));\n        return _originate(holder, f, termsHash);\n    }\n\n    /// @dev The external ABI deliberately exposes each signed term separately. Packing them\n    ///      into the already-storage-compatible `Facility` shape here keeps the gate below\n    ///      Solidity's stack limit without weakening or duplicating any validation.\n    function _originate(address holder, Facility memory f, bytes32 termsHash) private returns (uint256 tokenId) {\n        BridgeStorage storage $ = _storage();\n        bool mixed = BridgeMixedInterestLib.configured($.nextId);\n        if (holder == address(0)) revert Bridge_ZeroAddress();\n        // Facility defaults and protocol custody incidents share SGrove's uint256 event key.\n        // Confining sequential facility ids to the lower half makes the upper incident namespace\n        // structurally disjoint without changing any existing id or increment semantics.\n        if (!LossEventIds.isFacilityEvent($.nextId)) {\n            revert Bridge_FacilityEventNamespaceExhausted($.nextId);\n        }\n        if (\n            // State concentration is meaningful for tax-credit facilities only. A tax-credit\n            // origination must carry a state key; every other class must carry none, or the\n            // registry's state dimension is either bypassed or polluted by an unrelated class.\n            // THE SCHEDULE MUST CONTAIN AT LEAST ONE WHOLE INTERVAL BEFORE ITS FIRST PAYMENT.\n            // `WaterfallEngine.fund` anchors the PIK cursor at `nextPaymentDue - paymentInterval`\n            // so the capitalisation clock and the payment schedule agree by construction; with\n            // an interval longer than the first due date that subtraction underflows and `fund`\n            // reverts with a bare `Panic(0x11)`, stranding a fully attested facility in `Pending`\n            // with no diagnostic. The cursor write is unconditional, so a CASH-PAY facility was\n            // bricked by it too. Rejecting the terms here fails closed at the earliest point\n            // instead, and every legitimate schedule already satisfies it: `nextPaymentDue` is an\n            // absolute timestamp and `paymentInterval` a duration.\n            f.principal == 0 || f.borrowerId == bytes32(0) || f.fundingRecipient == address(0) || f.interestRateBps == 0\n                || f.interestRateBps > MAX_INTEREST_RATE_BPS || f.paymentInterval == 0\n                || (!mixed && f.paymentInterval > f.nextPaymentDue) || f.paymentScheduleHash == bytes32(0)\n                || f.offchainRef == bytes32(0)\n                || ((f.classId == Config.CLASS_FILM_TAX_CREDITS) == (f.stateId == bytes32(0)))\n        ) revert Bridge_BadFacility();\n\n        // The returned `true` keeps the linked delegatecall free of solc's codeless-target guard.\n        // Admission depends on the call completing; every refusal reverts with the recipient.\n        BridgeMixedInterestLib.requireFundingRecipientAllowed(f.fundingRecipient);\n\n        // -- on-chain conditions -------------------------------------------\n        ICollateralRegistry.ClassParams memory p = $.registry.classParams(f.classId);\n        if (f.ltvBps == 0 || f.ltvBps > p.maxLtvBps) revert Bridge_BadFacility();\n        if (f.maturity <= block.timestamp || f.maturity > block.timestamp + p.maxMaturity) {\n            revert Bridge_BadFacility();\n        }\n        if (f.nextPaymentDue <= block.timestamp || f.nextPaymentDue > f.maturity) revert Bridge_BadFacility();\n        if (f.rateType == RateType.Variable && f.rateIndexRef == bytes32(0)) revert Bridge_BadFacility();\n        if (f.rateType == RateType.Fixed && f.rateIndexRef != bytes32(0)) revert Bridge_BadFacility();\n        if (f.renewable != (f.renewalTermsHash != bytes32(0))) revert Bridge_BadFacility();\n        // PIK ONLY SERVICES FIXED / ACTUAL-360, SO REFUSE THE COMBINATION AT THE DOOR.\n        // `WaterfallEngine._planPik` reverts `Waterfall_PikRateTypeUnsupported` and\n        // `Waterfall_PikDayCountUnsupported` for anything else, and `capitalizePik` is the ONLY\n        // writer of `nextPaymentDue` for a PIK facility. Without this check a PIK facility could be\n        // created, or amended into, a shape whose crank can never run: the schedule would stop\n        // advancing immediately and the borrower would become permissionlessly markable past due,\n        // for a term combination the PROTOCOL has not implemented rather than anything they did.\n        //\n        // `pik` is set once at origination and `Amendment` deliberately does not carry it, so the\n        // two sides of this check can never be amended apart. Added 2026-09-10 after an adversarial\n        // round found the resulting freeze as the SEVENTH member of the PIK liveness family; the\n        // sheltering half of the fix is in `WaterfallEngine.pikCrankBlockedByProtocol`, and this is\n        // the half that stops the state arising at all.\n        if (f.pik && (f.rateType != RateType.Fixed || f.dayCountConvention != DayCountConvention.Actual360)) {\n            revert Bridge_BadFacility();\n        }\n        // AND THE THIRD SCOPE CONDITION, WHICH THE FIRST VERSION OF THIS GATE MISSED. `_planPik`\n        // enforces THREE things, not two: Fixed, Actual-360, and a RECEIVABLE class. Gating only\n        // the first two let a PIK facility be originated and FUNDED into a marked-to-market class,\n        // where it could then take interest in neither form: every `capitalizePik` reverts\n        // `Waterfall_PikClassNotReceivable`, and `distribute` refuses any PIK facility carrying an\n        // interest leg. A funded loan that can never earn or receive a wei, with nothing anywhere\n        // saying so. `CLASS_DIGITAL_ASSETS` is MarkedToMarket and active on this instance too, so\n        // this was reachable rather than theoretical, and it CANNOT be repaired afterwards: `pik`\n        // is written once at origination and the class is not amendable. Found by an adversarial\n        // round 2026-09-10, measured on a 500,000e18 digital-asset facility.\n        if (f.pik && p.model != ICollateralRegistry.CollateralModel.Receivable) revert Bridge_BadFacility();\n\n        // -- off-chain conditions: required attestations, all satisfied NOW -\n        // AUDIT FIX (P-32): every deal-identity attestation is bound to the same terms hash.\n        // Valuation is deliberately excluded: its payload is the mark, not a deal identity.\n        _requireMintAttestations($, f.classId, $.nextId, termsHash);\n\n        // -- marked-to-market extension (ADR-0015): fresh mark, value-bounded draw -\n        if (p.model == ICollateralRegistry.CollateralModel.MarkedToMarket) {\n            (uint256 value, uint64 asOf) = $.oracle.latestValuation($.nextId);\n            if (asOf == 0 || block.timestamp - asOf > p.maxMarkAge) {\n                revert Bridge_ValuationStale(0, asOf, p.maxMarkAge);\n            }\n            uint256 maxByValue = value * f.ltvBps / Config.BPS;\n            if (f.principal > maxByValue) revert Bridge_LtvExceedsValue(f.principal, maxByValue);\n        }\n\n        // -- concentration: enforced atomically in the registry ------------\n        $.registry.recordExposureIncrease(f.classId, f.borrowerId, f.stateId, f.principal);\n\n        tokenId = $.nextId++;\n        $.facilities[tokenId] = f;\n        _safeMint(holder, tokenId);\n        emit Originated(tokenId, f.classId, f.borrowerId, termsHash);\n    }\n\n    /// @notice Re-validates that a PENDING facility still satisfies its origination gate\n    ///         immediately before funding (AUDIT FIX M-01). Origination checks are\n    ///         point-in-time; a facility can sit pending while state decays. This re-runs\n    ///         the time-sensitive gates - class still active, maturity and the first payment\n    ///         due date not passed, every required attestation STILL satisfied (a revoked one\n    ///         now blocks funding), and\n    ///         for a marked-to-market class the mark still fresh and the draw still within\n    ///         the value bound - so capital never deploys against stale/expired state.\n    ///         Reverts on the first failure; `WaterfallEngine.fund` calls it before deploying.\n    /// @dev AUDIT FIX (H-4): re-runs the TERMS BINDING too, against the terms actually stored on\n    ///      the token. Fixing only `originate` would leave the funding path open - this function\n    ///      repeated the same existence-only read, so a facility whose `CreditIssued` quorum was\n    ///      revoked and re-attested to different terms could still draw capital.\n    /// @param tokenId The pending facility about to be funded.\n    function checkFundable(uint256 tokenId) external view {\n        _requireAccrualFresh();\n        BridgeStorage storage $ = _storage();\n        Facility storage f = _facility($, tokenId);\n        if (f.state != LoanState.Pending) revert Bridge_NotPending(tokenId);\n        ICollateralRegistry.ClassParams memory p = $.registry.classParams(f.classId);\n        if (!p.active) revert Bridge_ClassInactive(f.classId);\n        if (f.maturity <= block.timestamp) revert Bridge_FacilityMatured(tokenId);\n        if (f.nextPaymentDue <= block.timestamp) revert Bridge_BadFacility();\n        if (_accrualEnabled($)) _requireAccrualTerms(tokenId, f.pik, f.rateType, f.dayCountConvention);\n\n        // AUDIT FIX (P-32): re-check every deal-identity attestation against the stored terms;\n        // Valuation retains its mark payload and is checked below by its own freshness/value limb.\n        bytes32 expected = BridgeMixedInterestLib.commitment(tokenId);\n        if (expected == bytes32(0)) expected = _creditTermsHash(f);\n        _requireMintAttestations($, f.classId, tokenId, expected);\n\n        if (p.model == ICollateralRegistry.CollateralModel.MarkedToMarket) {\n            (uint256 value, uint64 asOf) = $.oracle.latestValuation(tokenId);\n            if (asOf == 0 || block.timestamp - asOf > p.maxMarkAge) {\n                revert Bridge_ValuationStale(tokenId, asOf, p.maxMarkAge);\n            }\n            uint256 maxByValue = value * f.ltvBps / Config.BPS;\n            if (f.principal > maxByValue) revert Bridge_LtvExceedsValue(f.principal, maxByValue);\n        }\n    }\n\n    /// @notice Retires a PENDING facility that will never be funded (AUDIT FIX M-02):\n    ///         atomically reverses its recorded book exposure and burns the position NFT,\n    ///         so an abandoned or erroneous origination cannot permanently consume\n    ///         class/borrower/state/total concentration headroom. Pending only - a funded\n    ///         facility must run its lifecycle. Originator-gated (symmetric with mint).\n    function cancelPending(uint256 tokenId) external onlyRole(Roles.ORIGINATOR_ROLE) nonReentrant {\n        _requireAccrualIdle();\n        BridgeStorage storage $ = _storage();\n        Facility storage f = _facility($, tokenId);\n        if (f.state != LoanState.Pending) revert Bridge_NotPending(tokenId);\n        // release exposure BEFORE burning: same-tx reversal keeps the concentration book\n        // and the NFT set describing the same reality (registry decrease is CREDIT_ROLE,\n        // which the bridge already holds for origination's increase).\n        $.registry.recordExposureDecrease(f.classId, f.borrowerId, f.stateId, f.principal);\n        f.state = LoanState.Cancelled;\n        emit StateChanged(tokenId, LoanState.Pending, LoanState.Cancelled);\n        _burn(tokenId);\n    }\n\n    // -- lifecycle state machine ------------------------------------------\n\n    /// @notice Advances a facility's lifecycle. Only the credit layer (CREDIT_ROLE -\n    ///         WaterfallEngine/DefaultManager in Phase E). Transitions are a strict\n    ///         guarded machine; anything else reverts.\n    function transitionState(uint256 tokenId, LoanState to) external onlyRole(Roles.CREDIT_ROLE) nonReentrant {\n        _requireAccrualIdle();\n        BridgeStorage storage $ = _storage();\n        Facility storage f = _facility($, tokenId);\n        LoanState from = f.state;\n        bool ok = (from == LoanState.Pending && to == LoanState.Active)\n            || (from == LoanState.Active && to == LoanState.Amortizing)\n            || ((from == LoanState.Active || from == LoanState.Amortizing) && to == LoanState.Repaid)\n            || ((from == LoanState.Active || from == LoanState.Amortizing) && to == LoanState.Defaulted)\n            || (from == LoanState.Defaulted && to == LoanState.Accelerated)\n        // AUDIT FIX (M-03): a defaulted/accelerated facility that recovers its full\n        // outstanding principal closes out to Resolved and unfreezes the position.\n        || ((from == LoanState.Defaulted || from == LoanState.Accelerated) && to == LoanState.Resolved);\n        if (!ok) revert Bridge_InvalidTransition(tokenId, from, to);\n        f.state = to;\n        emit StateChanged(tokenId, from, to);\n    }\n\n    /// @notice Whether a credit operation can presently update the bridge's guarded schedule.\n    /// @dev A temporary operation lock is not evidence that a borrower missed a payment.\n    function creditOperationIdle() external view returns (bool) {\n        return !_reentrancyGuardEntered();\n    }\n\n    /// @notice Advances the due date after an exact, attested payment.\n    function setNextPaymentDue(uint256 tokenId, uint64 nextDue) external onlyRole(Roles.CREDIT_ROLE) nonReentrant {\n        _requireAccrualIdle();\n        BridgeMixedInterestLib.setCashDue(tokenId, nextDue);\n    }\n\n    /// @inheritdoc IAccrualBridge\n    /// @dev This reserve-only continuation runs during bounded keeper accounting. It deliberately\n    ///      has no source-idle or freshness gate; it cannot amend terms, invent a maturity extension,\n    ///      alter cash due dates or accept the coordinator's terminal zero sentinel.\n    function setAccruedPaymentDue(uint256 tokenId, uint64 nextDue) external {\n        BridgeMixedInterestLib.setPikDue(tokenId, nextDue);\n    }\n\n    /// @notice Applies a quorum-attested servicing amendment or renewal.\n    function amendTerms(uint256 tokenId, bytes32 amendmentId, Amendment calldata a)\n        external\n        onlyRole(Roles.ORIGINATOR_ROLE)\n        whenNotPaused\n        nonReentrant\n    {\n        _requireAccrualFresh();\n        BridgeMixedInterestLib.amendTerms(tokenId, amendmentId, abi.encode(a));\n    }\n\n    // -- views ------------------------------------------------------------\n\n    /// @notice Full facility record (reverts for unknown tokens).\n    function facility(uint256 tokenId) external view returns (Facility memory) {\n        return _facility(_storage(), tokenId);\n    }\n\n    /// @notice The `CreditIssued` payload an attester quorum must sign to authorize a facility\n    ///         on EXACTLY these terms (AUDIT FIX H-4). Attester tooling and the mint gate derive\n    ///         the commitment from this one function, so they cannot drift apart.\n    /// @dev The facility id is NOT in the preimage because it is the oracle record's key and is\n    ///      already covered by the EIP-712 digest (`AttestationOracle.attest` hashes\n    ///      `a.facilityId`). The per-facility interest rate IS in the preimage: pricing is a\n    ///      signed loan term, not a collateral-class parameter.\n    /// @param terms Complete contractual and operational facility terms.\n    /// @return The terms commitment.\n    function creditTermsHash(OriginationTerms calldata terms) external pure returns (bytes32) {\n        return keccak256(abi.encode(terms));\n    }\n\n    function mixedInterestTerms(uint256 tokenId)\n        external\n        view\n        returns (BridgeMixedInterestLib.InterestLegTerms memory)\n    {\n        _facility(_storage(), tokenId);\n        return BridgeMixedInterestLib.terms(tokenId);\n    }\n\n    function isMixedInterest(uint256 tokenId) external view returns (bool) {\n        _facility(_storage(), tokenId);\n        return BridgeMixedInterestLib.configured(tokenId);\n    }\n\n    function _creditTermsHash(Facility memory f) private pure returns (bytes32) {\n        OriginationTerms memory t = OriginationTerms({\n            classId: f.classId,\n            borrowerId: f.borrowerId,\n            stateId: f.stateId,\n            principal: f.principal,\n            ltvBps: f.ltvBps,\n            interestRateBps: f.interestRateBps,\n            maturity: f.maturity,\n            fundingRecipient: f.fundingRecipient,\n            paymentInterval: f.paymentInterval,\n            nextPaymentDue: f.nextPaymentDue,\n            rateType: f.rateType,\n            dayCountConvention: f.dayCountConvention,\n            renewable: f.renewable,\n            paymentScheduleHash: f.paymentScheduleHash,\n            rateIndexRef: f.rateIndexRef,\n            renewalTermsHash: f.renewalTermsHash,\n            offchainRef: f.offchainRef,\n            pik: f.pik\n        });\n        return keccak256(abi.encode(t));\n    }\n\n    function _facilityFrom(OriginationTerms calldata terms) private pure returns (Facility memory f) {\n        f.classId = terms.classId;\n        f.borrowerId = terms.borrowerId;\n        f.stateId = terms.stateId;\n        f.principal = terms.principal;\n        f.ltvBps = terms.ltvBps;\n        f.interestRateBps = terms.interestRateBps;\n        f.maturity = terms.maturity;\n        f.fundingRecipient = terms.fundingRecipient;\n        f.paymentInterval = terms.paymentInterval;\n        f.nextPaymentDue = terms.nextPaymentDue;\n        f.rateType = terms.rateType;\n        f.dayCountConvention = terms.dayCountConvention;\n        f.renewable = terms.renewable;\n        f.paymentScheduleHash = terms.paymentScheduleHash;\n        f.rateIndexRef = terms.rateIndexRef;\n        f.renewalTermsHash = terms.renewalTermsHash;\n        f.offchainRef = terms.offchainRef;\n        f.pik = terms.pik;\n        f.state = LoanState.Pending;\n    }\n\n    /// @notice Required mint-attestation mask for a class.\n    function requiredMintAttestations(uint256 classId) external view returns (uint256) {\n        return _storage().requiredMintAttestations[classId];\n    }\n\n    /// @notice Wired module addresses (post-deploy validation aid).\n    function modules() external view returns (address registry, address oracle) {\n        BridgeStorage storage $ = _storage();\n        return (address($.registry), address($.oracle));\n    }\n\n    /// @notice Total facilities ever originated.\n    function totalOriginated() external view returns (uint256) {\n        return _storage().nextId - 1;\n    }\n\n    // -- guardian ---------------------------------------------------------\n\n    /// @notice Pauses origination. Emergency use only.\n    function pause() external onlyRole(Roles.GUARDIAN_ROLE) {\n        _requireAccrualIdle();\n        _pause();\n    }\n\n    /// @notice Unpauses origination.\n    function unpause() external onlyRole(Roles.GUARDIAN_ROLE) {\n        _requireAccrualIdle();\n        _unpause();\n    }\n\n    // -- internals --------------------------------------------------------\n\n    /// @dev Transfer restriction: positions move only under governance execution\n    ///      (custody changes are legal events), and NEVER while frozen\n    ///      (Defaulted/Accelerated) - the on-chain half of the dual-record freeze.\n    function _update(address to, uint256 tokenId, address auth) internal override returns (address from) {\n        _requireAccrualIdle();\n        BridgeStorage storage $ = _storage();\n        address owner = _ownerOf(tokenId);\n        if (owner != address(0)) {\n            LoanState st = $.facilities[tokenId].state;\n            if (st == LoanState.Defaulted || st == LoanState.Accelerated) revert Bridge_PositionFrozen(tokenId);\n            if (to != address(0) && !hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) revert Bridge_TransferRestricted();\n        }\n        return super._update(to, tokenId, auth);\n    }\n\n    /// @dev AUDIT FIX (P-32). Requires every selected mint-gate attestation to be currently\n    ///      satisfied. AssignmentExecuted, UCCFiled and CreditIssued are deal identity facts and\n    ///      must carry the exact `creditTermsHash`; Valuation is intentionally left on its own mark\n    ///      payload and checked by the marked-to-market branch.\n    function _requireMintAttestations(BridgeStorage storage $, uint256 classId, uint256 facilityId, bytes32 termsHash)\n        private\n        view\n    {\n        uint256 mask = $.requiredMintAttestations[classId];\n        // An unset class must satisfy the same mandatory gate as a configured class.\n        if (mask & BIT_CREDIT_ISSUED == 0) revert Bridge_BadAttestationMask(mask);\n        // Preserve the original missing-attestation precedence: a present bit is checked before\n        // any payload comparison, so a genuinely absent documentary fact remains\n        // `Bridge_AttestationMissing` rather than looking like a malformed commitment.\n        for (uint256 k = 0; k < KIND_COUNT; ++k) {\n            if (mask & (1 << k) == 0) continue;\n            IAttestationOracle.AttestationKind kind = IAttestationOracle.AttestationKind(uint8(k));\n            (,, bool ok) = $.oracle.latestPayload(facilityId, kind);\n            if (!ok) revert Bridge_AttestationMissing(classId, kind);\n        }\n\n        // ORDER IS LOAD-BEARING BELOW THIS LINE. DO NOT REORDER, AND DO NOT NARROW THE LOOP ABOVE.\n        //\n        // Both remaining `latestPayload` reads in this function DISCARD the `ok` flag, and that is\n        // safe ONLY because of what the loop above has already done: it reverts\n        // `Bridge_AttestationMissing` for EVERY bit set in `mask`, over the same\n        // `0..KIND_COUNT-1` range these two reads are gated on, and this function is `view` so the\n        // oracle cannot change underneath them. Under those three conditions a dropped `ok` cannot\n        // hide an absent attestation, because an absent one has already reverted.\n        //\n        // Reorder these blocks above the loop, narrow the loop's range or its mask, or make this\n        // function non-view, and BOTH reads below become real defects: a missing attestation would\n        // read as `payload == bytes32(0)` and be compared against `termsHash` rather than refused.\n        // Recorded 2026-09-10 during the first Slither triage on this tree, which dispositioned\n        // these two `unused-return` findings as safe on exactly this reasoning. A property that\n        // holds by ordering has to be stated where someone would break it.\n        //\n        // Check the existing terms-quorum limb first to preserve H-4's established error surface.\n        // Documentary payloads are then checked below; P-32 adds those checks without changing the\n        // diagnostics callers already receive for a mismatched CreditIssued bundle.\n        if (mask & BIT_CREDIT_ISSUED != 0) {\n            (bytes32 payload,,) = $.oracle.latestPayload(facilityId, IAttestationOracle.AttestationKind.CreditIssued);\n            if (payload != termsHash) {\n                revert Bridge_TermsNotAttested(facilityId, termsHash, payload);\n            }\n        }\n\n        for (uint256 k = 0; k < KIND_COUNT; ++k) {\n            if (mask & (1 << k) == 0) continue;\n            IAttestationOracle.AttestationKind kind = IAttestationOracle.AttestationKind(uint8(k));\n            if (_isDealIdentityKind(kind) && kind != IAttestationOracle.AttestationKind.CreditIssued) {\n                (bytes32 payload,,) = $.oracle.latestPayload(facilityId, kind);\n                if (payload != termsHash) {\n                    revert Bridge_AttestationNotBoundToDeal(classId, kind, termsHash, payload);\n                }\n            }\n        }\n    }\n\n    function _isDealIdentityKind(IAttestationOracle.AttestationKind kind) private pure returns (bool) {\n        return kind == IAttestationOracle.AttestationKind.AssignmentExecuted\n            || kind == IAttestationOracle.AttestationKind.UCCFiled\n            || kind == IAttestationOracle.AttestationKind.CreditIssued;\n    }\n\n    function _facility(BridgeStorage storage $, uint256 tokenId) private view returns (Facility storage f) {\n        if (tokenId == 0 || tokenId >= $.nextId) revert Bridge_UnknownToken(tokenId);\n        f = $.facilities[tokenId];\n    }\n\n    function supportsInterface(bytes4 interfaceId)\n        public\n        view\n        override(ERC721Upgradeable, AccessControlUpgradeable)\n        returns (bool)\n    {\n        return super.supportsInterface(interfaceId);\n    }\n\n    /// @dev Token approvals cannot change during a source accounting or delivery callback.\n    function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal override {\n        _requireAccrualIdle();\n        super._approve(to, tokenId, auth, emitEvent);\n    }\n\n    /// @dev Operator approvals share the same callback boundary as ownership changes.\n    function _setApprovalForAll(address owner, address operator, bool approved) internal override {\n        _requireAccrualIdle();\n        super._setApprovalForAll(owner, operator, approved);\n    }\n\n    /// @dev Includes initial grants before binding and governed grants afterwards.\n    function _grantRole(bytes32 role, address account) internal override returns (bool) {\n        _requireAccrualIdle();\n        return super._grantRole(role, account);\n    }\n\n    /// @dev Includes revocation and a holder's own role renunciation.\n    function _revokeRole(bytes32 role, address account) internal override returns (bool) {\n        _requireAccrualIdle();\n        return super._revokeRole(role, account);\n    }\n\n    /// @dev An upgrade cannot replace lifecycle accounting during a protected source operation.\n    function _authorizeUpgrade(address implementation) internal view override onlyRole(Roles.UPGRADER_ROLE) {\n        _requireAccrualIdle();\n        if (BridgeMixedInterestLib.enabled()) BridgeAccrualLib.validateMixedImplementation(implementation);\n    }\n\n    /// @dev Admissions and prospective economic amendments require the authoritative current book.\n    function _requireAccrualFresh() private view {\n        address reserve = _storage().accrualReserve;\n        if (reserve != address(0)) IContinuousAccrual(reserve).requireAccrualFresh();\n    }\n\n    /// @dev Recovery, governance and custody changes need an idle source, independent of keeper lag.\n    function _requireAccrualIdle() private view {\n        address reserve = _storage().accrualReserve;\n        if (reserve != address(0)) IAccrualExposure(reserve).requireAccrualIdle();\n    }\n\n    /// @dev Binding prepares modules before activation and does not rewrite legacy funded terms.\n    function _accrualEnabled(BridgeStorage storage $) private view returns (bool) {\n        return $.accrualReserve != address(0) && IContinuousAccrual($.accrualReserve).accrualSnapshot().enabled;\n    }\n\n    /// @dev Continuous cash supports fixed Actual/360 and Actual/365; PIK retains fixed Actual/360.\n    function _requireAccrualTerms(uint256 tokenId, bool pik, RateType rateType, DayCountConvention dayCount)\n        private\n        pure\n    {\n        if (\n            rateType != RateType.Fixed || dayCount == DayCountConvention.Thirty360\n                || (pik && dayCount != DayCountConvention.Actual360)\n        ) revert Bridge_AccrualUnsupportedTerms(tokenId);\n    }\n\n    function _storage() private pure returns (BridgeStorage storage $) {\n        assembly {\n            $.slot := BRIDGE_STORAGE_LOCATION\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol","source_code":"// 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"},{"file_path":"src/interfaces/IReserveManager.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\n/// @title IReserveManager\n/// @notice Mainnet-v1 treasury for canonical USDC and deployed facility principal.\n/// @dev USD values use 18 decimals. USDC amounts use the token's native 6 decimals.\ninterface IReserveManager {\n    /// @notice Recognition or an opening import makes a return to legacy accounting unsafe.\n    error ReserveManager_LegacyRollbackUnsafe();\n\n    /// @notice Refuses a legacy-code rollback once accrual activation or migration has started.\n    /// @dev Read-only execution guard for a governance batch, not authority to upgrade.\n    function requireLegacyRollbackSafe() external view;\n\n    /// @notice Canonical USDC was pulled into recorded idle custody.\n    event USDCDeposited(address indexed from, uint256 requested, uint256 credited);\n    /// @notice Canonical USDC was released from recorded idle custody.\n    event USDCReleased(address indexed to, uint256 amount);\n    /// @notice A permissionless observation compared recorded and live USDC custody.\n    event IdleUSDCObserved(uint256 recorded, uint256 live, uint256 shortfall);\n    /// @notice An adjudicated custody loss reduced recorded idle backing.\n    event IdleUSDCWrittenDown(uint256 amount, uint256 remaining);\n    /// @notice Returned USDC was credited against one arm's written-down recovery capacity.\n    event RecoveredIdleUSDCCredited(\n        uint256 indexed armId, uint256 nativeUnits, uint256 value, bytes32 indexed evidenceHash\n    );\n    /// @notice A custody loss reduced backing and fixed the supply reduction the cascade must absorb.\n    event ReserveLossRecognized(\n        uint256 indexed incidentId, uint256 backingReduction, uint256 surplusAbsorbed, uint256 supplyReductionRequired\n    );\n    /// @notice The complete surplus-to-senior allocation of one recognized custody loss.\n    event ReserveLossAllocated(\n        uint256 indexed incidentId,\n        uint256 backingReduction,\n        uint256 surplusAbsorbed,\n        uint256 curatorAbsorbed,\n        uint256 backstopCovered,\n        uint256 seniorBurned,\n        uint256 residualDeficit\n    );\n    /// @notice The controller used for supply, backing, and loss-burn checks changed.\n    event LossControllerSet(address indexed previousController, address indexed newController);\n    /// @notice The ordered custody-cascade and governance timing modules were wired.\n    event ReserveLossModulesSet(\n        address indexed curator, address indexed backstop, address indexed vault, address governor, address timelock\n    );\n    /// @notice A Guardian created a persistent reserve-loss interlock and evidence commitment.\n    event ReserveLossArmed(uint256 indexed armId, uint256 indexed incidentId, bytes32 evidenceHash);\n    /// @notice Governance cancelled an unused arm and disabled future Guardian arms.\n    event ReserveLossArmCancelled(uint256 indexed armId, bytes32 indexed evidenceHash);\n    /// @notice Governance cancelled a custody false alarm while retaining all credit marks.\n    event UnratifiedReserveLossArmCancelled(\n        uint256 indexed armId, bytes32 indexed evidenceHash, uint256 retainedPrincipalImpairment\n    );\n    /// @notice A previously ratified arm must use the incident settlement path.\n\n    error ReserveManager_ArmAlreadyRatified(uint256 armId);\n\n    /// @notice Governance closed the arm-bound incident and disabled future Guardian arms.\n    event ReserveLossArmFinalized(uint256 indexed armId, uint256 indexed incidentId, bytes32 indexed evidenceHash);\n    /// @notice Governance ratified and executed the current objective custody shortfall.\n    event ReserveLossRatified(\n        uint256 indexed armId,\n        uint256 indexed incidentId,\n        uint256 approvedMaxLoss,\n        uint256 actualLoss,\n        bytes32 evidenceHash\n    );\n    /// @notice Governance enabled or disabled creation of new Guardian reserve-loss arms.\n    event GuardianReserveLossArmsEnabled(bool enabled);\n    /// @notice A custody-loss incident entered the active register under its bound arm.\n    event ReserveLossIncidentOpened(uint256 indexed incidentId, uint256 indexed armId, bytes32 evidenceHash);\n    /// @notice The active custody-loss incident left the register.\n    event ReserveLossIncidentClosed(uint256 indexed incidentId);\n    /// @notice A cascade changed the latched unabsorbed reserve deficit.\n    event ReserveDeficitUpdated(uint256 indexed incidentId, uint256 previousDeficit, uint256 currentDeficit);\n    /// @notice Governance cleared a cured reserve-deficit latch with supporting evidence.\n    event ReserveDeficitResolved(uint256 previousDeficit, bytes32 evidenceHash);\n    /// @notice Idle USDC became deployed principal for a facility.\n    event PrincipalDeployed(uint256 indexed facilityId, uint256 amount);\n    /// @notice A retained origination fee became additional facility principal.\n    event FeeCapitalized(uint256 indexed facilityId, uint256 amount);\n\n    /// @notice Contractually accrued PIK interest joined a facility's deployed principal.\n    /// @dev No cash moved and, unlike `FeeCapitalized`, none was retained either.\n    /// @param facilityId The facility.\n    /// @param amount 18-decimal value capitalised.\n    /// @param deployedAfter The facility's deployed principal after the act.\n    event PikCapitalized(uint256 indexed facilityId, uint256 amount, uint256 deployedAfter);\n    /// @notice A cash receipt increased idle custody and reduced the stated principal leg.\n    event PaymentReceived(\n        uint256 indexed facilityId, address indexed payer, uint256 usdcAmount, uint256 principalReturned\n    );\n    /// @notice Realized facility principal was removed from backing.\n    event PrincipalWrittenDown(uint256 indexed facilityId, uint256 amount);\n    /// @notice Governance added an evidence-backed conservative facility impairment.\n    event PrincipalImpairmentRecognized(\n        uint256 indexed facilityId,\n        uint256 amount,\n        uint256 facilityImpairment,\n        uint256 totalImpairment,\n        uint256 backingAfter,\n        bytes32 evidenceHash\n    );\n    /// @notice Governance released part of an evidence-backed conservative facility impairment.\n    event PrincipalImpairmentReleased(\n        uint256 indexed facilityId,\n        uint256 amount,\n        uint256 facilityImpairment,\n        uint256 totalImpairment,\n        bytes32 evidenceHash\n    );\n    /// @notice A principal write-down consumed the corresponding previously recognized impairment.\n    event PrincipalImpairmentRealized(\n        uint256 indexed facilityId, uint256 amount, uint256 facilityImpairment, uint256 totalImpairment\n    );\n    /// @notice The retained compatibility loss-absorber binding changed.\n    event LossAbsorberSet(address indexed previousAbsorber, address indexed newAbsorber);\n    /// @notice A funder supplied new canonical USDC backing without minting claims.\n    event Recapitalized(\n        address indexed funder, uint256 units, uint256 credited, uint256 backingAfter, uint256 deficitOutstanding\n    );\n    /// @notice A senior-exit junior draw was added to the historical prepayment ledger.\n    event ExitPrepaymentRecorded(uint256 amount, uint256 outstanding);\n    /// @notice A facility loss consumed part of the historical exit-prepayment ledger.\n    event ExitPrepaymentConsumed(uint256 indexed facilityId, uint256 consumed, uint256 outstanding);\n    /// @notice A custody loss consumed the surplus backing part of an exit prepayment.\n    event ExitPrepaymentAbsorbedByCustody(uint256 indexed incidentId, uint256 consumed, uint256 outstanding);\n    /// @notice Governance permanently bound the borrower-payout policy used before USDC deployment.\n    event BorrowerPayoutRegistrySet(address indexed registry);\n\n    /// @notice Requested USDC value exceeds recorded idle value.\n    error ReserveManager_InsufficientIdleValue(uint256 requestedValue, uint256 idleValue);\n    /// @notice Requested principal reduction exceeds the facility's live deployed principal.\n    error ReserveManager_InsufficientDeployedPrincipal(uint256 facilityId, uint256 requested, uint256 deployed);\n    /// @notice A value-moving call supplied a zero amount.\n    error ReserveManager_ZeroAmount();\n    /// @notice A required account or module address is zero.\n    error ReserveManager_ZeroAddress();\n    /// @notice The caller is not an authorised controller or credit depositor.\n    error ReserveManager_NotDepositor(address caller);\n    /// @notice A pull expected canonical USDC but received no value.\n    error ReserveManager_NoValueReceived();\n    /// @notice The token balance delta differed from the requested USDC transfer.\n    error ReserveManager_UnexpectedUSDCReceipt(uint256 expected, uint256 received);\n    /// @notice A legacy idle write-down exceeds recorded idle value.\n    error ReserveManager_WriteDownExceedsIdle(uint256 amount, uint256 idle);\n    /// @notice A USDC release or deployment attempted to target the ReserveManager itself.\n    error ReserveManager_SelfDeployment();\n    /// @notice An 18-decimal value cannot be represented exactly in native USDC units.\n    error ReserveManager_ValueNotUSDCExact(uint256 value);\n    /// @notice The configured custody token does not use canonical USDC's six decimals.\n    error ReserveManager_InvalidUSDCDecimals(uint8 decimals);\n    /// @notice A payment allocated more principal than the USDC value actually received.\n    error ReserveManager_PrincipalExceedsPayment(uint256 principal, uint256 paymentValue);\n    /// @notice A proposed curator, backstop, vault, or absorber fails its binding contract.\n    error ReserveManager_InvalidLossAbsorber(address absorber);\n    /// @notice A proposed controller fails its module and reserve binding contract.\n    error ReserveManager_InvalidLossController(address controller);\n    /// @notice A loss layer's reported burn differs from the observed USDfr supply reduction.\n    error ReserveManager_LossAbsorberContractViolated(uint256 backingReduction, uint256 supplyBurned);\n    /// @notice Reported cascade allocation does not reconcile to the recognized loss.\n    error ReserveManager_LossAllocationMismatch(\n        uint256 expectedSurplus, uint256 reportedSurplus, uint256 expectedAccounted, uint256 reportedAccounted\n    );\n    /// @notice The terminal live supply/backing deficit differs from the cascade calculation.\n    error ReserveManager_PostLossDeficitMismatch(uint256 expectedDeficit, uint256 observedDeficit);\n    /// @notice A custody incident id has already been consumed.\n    error ReserveManager_IncidentAlreadyUsed(uint256 incidentId);\n    /// @notice A new arm or incident cannot replace the currently active incident.\n    error ReserveManager_IncidentAlreadyActive(uint256 incidentId);\n    /// @notice A terminal action requires an active custody incident.\n    error ReserveManager_NoActiveIncident();\n    /// @notice The supplied custody incident does not match the active incident.\n    error ReserveManager_IncidentMismatch(uint256 expected, uint256 supplied);\n    /// @notice The caller lacks the reserve-administration authority required for the live loss path.\n    error ReserveManager_ReserveLossCallerNotAdmin(address caller);\n    /// @notice A reserve-loss allocation used an id outside the custody-event namespace.\n    error ReserveManager_InvalidReserveLossIncident(uint256 incidentId);\n    /// @notice A cascade was requested without a recognized supply reduction.\n    error ReserveManager_NoRecognizedReserveLoss();\n    /// @notice Finalization was attempted while recognized loss remains unallocated.\n    error ReserveManager_RecognizedLossOutstanding(uint256 amount);\n    /// @notice Finalization was attempted while live USDC custody remains short.\n    error ReserveManager_LiveShortfallExists(uint256 nativeUnits);\n    /// @notice Finalization was attempted while supply still exceeds backing.\n    error ReserveManager_DeficitStillExists(uint256 recordedDeficit, uint256 observedDeficit);\n    /// @notice Creation of new Guardian reserve-loss arms is disabled.\n    error ReserveManager_GuardianArmsDisabled();\n    /// @notice A new arm cannot replace the currently active arm.\n    error ReserveManager_ArmAlreadyActive(uint256 armId);\n    /// @notice An arm-bound action requires an active arm.\n    error ReserveManager_NoActiveArm();\n    /// @notice The supplied arm id does not match the active arm.\n    error ReserveManager_ArmMismatch(uint256 expected, uint256 supplied);\n    /// @notice Ratification evidence does not match the Guardian's armed commitment.\n    error ReserveManager_ArmEvidenceMismatch(bytes32 expected, bytes32 supplied);\n    /// @notice The monotonic arm id space is exhausted.\n    error ReserveManager_ArmIdExhausted();\n    /// @notice Ratification found that the objective custody shortfall was already cured.\n    error ReserveManager_ShortfallCured();\n    /// @notice The live custody loss exceeds governance's approved maximum.\n    error ReserveManager_LossExceedsApproval(uint256 actualLoss, uint256 approvedMaxLoss);\n    /// @notice No physically returned USDC is available for the supplied arm.\n    error ReserveManager_NoRecoveredUSDC(uint256 armId);\n    /// @notice Finalization found returned USDC that has not yet been credited.\n    error ReserveManager_RecoveredUSDCNotCredited(uint256 armId, uint256 nativeUnits);\n    /// @notice The superseded arbitrary idle-write-down entry is permanently disabled.\n    error ReserveManager_LegacyPathDisabled();\n    /// @notice Cancellation would release an interlock while a loss condition remains live.\n    error ReserveManager_InterlockReleaseForbidden();\n    /// @notice Loss-module rebinding is forbidden while an arm, incident, shortfall, or deficit is live.\n    error ReserveManager_ModuleRebindForbidden();\n    /// @notice The proposed governor and timelock do not expose one coherent live timing path.\n    error ReserveManager_InvalidGovernanceTiming(address governor, address timelock);\n    /// @notice An evidence-backed transition supplied the zero evidence hash.\n    error ReserveManager_ZeroEvidenceHash();\n    /// @notice A conservative impairment would exceed the facility's remaining face principal.\n    error ReserveManager_ImpairmentExceedsFace(uint256 facilityId, uint256 requested, uint256 remainingFace);\n    /// @notice An impairment release exceeds the amount currently recognized for the facility.\n    error ReserveManager_ImpairmentReleaseExceedsRecognized(uint256 facilityId, uint256 requested, uint256 recognized);\n    /// @notice The caller is not the retained compatibility loss absorber.\n    error ReserveManager_NotLossAbsorber(address caller);\n    /// @notice Recorded idle USDC exceeds live custody, so a protected out-door is closed.\n    error ReserveManager_IdleCustodyShortfall(uint256 recordedUnits, uint256 liveUnits);\n    /// @notice A legacy incident nonce is zero or enters the reserved custody namespace.\n    error ReserveManager_InvalidIncidentNonce(uint256 incidentNonce);\n    /// @notice Deficit resolution was requested without a recorded deficit.\n    error ReserveManager_NoReserveDeficit();\n    /// @notice An incident close requires its recorded deficit to be resolved first.\n    error ReserveManager_DeficitResolutionRequired(uint256 recordedDeficit);\n    /// @notice The borrower-payout policy was already bound and cannot be replaced.\n    error BorrowerPayout_RegistryAlreadySet(address registry);\n    /// @notice A proposed borrower-payout policy has no compatible code.\n    error BorrowerPayout_InvalidRegistry(address registry);\n    /// @notice Loan proceeds may not be directed to this address.\n    error BorrowerPayout_RecipientNotAllowed(address recipient);\n\n    /// @notice Pulls exact canonical USDC from `from` into recorded idle custody.\n    function depositUSDC(address from, uint256 amount) external returns (uint256 credited);\n    /// @notice Releases recorded idle USDC through the controller-only redemption path.\n    function releaseUSDC(address to, uint256 amount) external;\n\n    /// @notice Permanently binds the timelock-managed borrower-payout registry.\n    function setBorrowerPayoutRegistry(address registry) external;\n\n    /// @notice The permanent borrower-payout policy, or zero before the required binding.\n    function borrowerPayoutRegistry() external view returns (address);\n\n    /// @notice Permissionlessly checkpoints the objective live-vs-recorded custody shortfall.\n    /// @dev Observation never changes backing and never moves junior or senior capital.\n    /// @return shortfall Native six-decimal USDC units missing from custody.\n    function reconcileIdleUSDC() external returns (uint256 shortfall);\n\n    /// @notice Permissionless live-vs-recorded custody observation; never changes accounting.\n    function observeIdleUSDC() external view returns (uint256 recorded, uint256 live, uint256 shortfall);\n\n    /// @notice Native USDC units by which recorded idle custody exceeds the live token balance.\n    function idleCustodyShortfall() external view returns (uint256);\n    /// @notice Recorded backing net of any physically observable idle-custody shortfall.\n    function recognizedBackingValue() external view returns (uint256);\n    /// @notice Whether an arm, incident, recognized loss, deficit, or live shortfall locks exits.\n    function custodyLossUnabsorbed() external view returns (bool);\n\n    /// @notice Wires the controller used for direct supply/backing and loss-burn checks.\n    function setLossController(address controller) external;\n    /// @notice Wires the retained compatibility absorber after verifying its reserve binding.\n    function setLossAbsorber(address absorber) external;\n\n    /// @notice Legacy incident controls retained as non-credit compatibility surfaces while\n    ///         new custody accounting uses the arm-bound ratification path.\n    function openReserveLossIncident(uint256 incidentNonce, bytes32 evidenceHash)\n        external\n        returns (uint256 incidentId);\n    /// @notice Closes the exact active legacy incident once no deficit remains.\n    function closeReserveLossIncident(uint256 incidentId) external;\n    /// @notice Clears a cured legacy reserve-deficit latch with supporting evidence.\n    function resolveReserveDeficit(bytes32 evidenceHash) external;\n    /// @notice Canonical USDC held above the amount recorded as idle custody.\n    function unrecordedUSDC() external view returns (uint256);\n\n    /// @notice Wires the ordered custody cascade and its live governance timing sources.\n    function setReserveLossModules(address curator, address backstop, address vault, address governor, address timelock)\n        external;\n\n    /// @notice Guardian-only persistent interlock created before an amount-bearing proposal.\n    /// @return armId Monotonic internal id consumed only by an explicit governance terminal action.\n    /// @return incidentId Structurally bound upper-half custody event id.\n    function armReserveLossFreeze(bytes32 evidenceHash) external returns (uint256 armId, uint256 incidentId);\n\n    /// @notice Governance consumes an unused arm only when the objective shortfall is zero and\n    ///         no adjudicated loss, incident or deficit exists; future Guardian arms stay disabled.\n    function cancelAndDisable(uint256 expectedArmId, bytes32 evidenceHash) external;\n\n    /// @notice Cancels an unratified custody false alarm and disables further guardian arms.\n    /// @dev Requires accounted custody and no unsettled custody incident or reserve deficit.\n    ///      Independent credit impairment and exit prepayments remain unchanged.\n    /// @param expectedArmId Exact active arm being cancelled.\n    /// @param evidenceHash Nonzero commitment to the governance resolution evidence.\n    function cancelUnratifiedArm(uint256 expectedArmId, bytes32 evidenceHash) external;\n\n    /// @notice Governance kill switch for repeated Guardian arms.\n    function setGuardianReserveLossArmsEnabled(bool enabled) external;\n\n    /// @notice Governance ratifies and atomically absorbs the live objective shortfall, bounded\n    ///         by the amount approved in the proposal. Every tranche under an arm reuses its id\n    ///         and must supply the Guardian's exact armed evidence commitment.\n    function ratifyAndOpen(uint256 expectedArmId, bytes32 evidenceHash, uint256 approvedMaxLoss)\n        external\n        returns (uint256 incidentId, uint256 actualLoss);\n\n    /// @notice Credits physically returned canonical USDC without minting USDfr, capped by the\n    ///         amount previously written down under `armId`. May execute after incident closure.\n    function creditRecoveredIdleUSDC(uint256 armId, bytes32 evidenceHash) external returns (uint256 credited);\n\n    /// @notice Atomically resolves a cured deficit, closes the arm-bound incident and disables\n    ///         future Guardian arms. It cannot release a shortfall or uncredited returned USDC.\n    function finalizeAndDisable(uint256 expectedArmId, bytes32 evidenceHash) external;\n\n    /// @notice Pulls new canonical USDC backing without minting USDfr claims.\n    function recapitalize(uint256 amount) external returns (uint256 credited);\n\n    /// @notice Controller used for supply, backing, and loss-burn verification.\n    function lossController() external view returns (address);\n    /// @notice Ordered curator, backstop, vault, governor, and timelock bindings.\n    function reserveLossModules()\n        external\n        view\n        returns (address curator, address backstop, address vault, address governor, address timelock);\n    /// @notice Active custody incident id and its evidence commitment.\n    function activeReserveLossIncident() external view returns (uint256 incidentId, bytes32 evidenceHash);\n    /// @notice Whether a custody incident id has already entered the durable register.\n    function reserveLossIncidentUsed(uint256 incidentId) external view returns (bool);\n    /// @notice Latched portion of adjudicated custody losses not absorbed by any capital layer.\n    function reserveDeficit() external view returns (uint256);\n    /// @notice Current recognized backing reduction and pending cascade requirement.\n    function recognizedReserveLoss()\n        external\n        view\n        returns (uint256 backingReduction, uint256 surplusAbsorbed, uint256 supplyReductionRequired);\n    /// @notice Active arm identity, derived incident, armed evidence, and future-arm switch.\n    function reserveLossArm()\n        external\n        view\n        returns (uint256 armId, uint256 incidentId, bytes32 evidenceHash, bool armsEnabled);\n    /// @notice Native USDC recovery capacity created by write-downs under one arm.\n    function reserveLossRecoveryCapacity(uint256 armId) external view returns (uint256 nativeUnits);\n    /// @notice Retained compatibility absorber bound to this reserve.\n    function lossAbsorber() external view returns (address);\n    /// @notice Historical junior prepayment still available for impairment release.\n    function exitPrepaidAbsorption() external view returns (uint256);\n    /// @notice Records a senior-exit junior draw in the compatibility prepayment ledger.\n    function recordExitPrepayment(uint256 amount) external;\n    /// @notice Consumes prepayment only against recognized impairment for a facility loss.\n    function consumeExitPrepayment(uint256 facilityId, uint256 loss) external returns (uint256 used);\n\n    /// @notice Shared fail-closed interlock consumed by curator withdrawals and queue settlement.\n    function reserveLossExitsLocked() external view returns (bool);\n\n    /// @notice Backwards-compatible semantic alias used by CuratorModule.\n    function curatorWithdrawalsLocked() external view returns (bool);\n\n    /// @notice Converts exact recorded idle USDC into deployed facility principal.\n    function recordDeployment(uint256 facilityId, address to, uint256 usdcAmount) external;\n    /// @notice Adds retained origination-fee cash as facility principal without moving custody.\n    function recordFeeCapitalization(uint256 facilityId, uint256 amount) external;\n\n    /// @notice Capitalises accrued PIK interest into a facility's deployed principal. No cash moves.\n    /// @dev CREDIT_ROLE, and in practice `WaterfallEngine.capitalizePik` alone, which carries every\n    ///      bound. See `ReserveManager.recordPikCapitalization` for why there is no idle check.\n    /// @param facilityId The facility.\n    /// @param amount 18-decimal value to capitalise, exact on the USDC grid.\n    function recordPikCapitalization(uint256 facilityId, uint256 amount) external;\n\n    /// @notice Atomically pulls exact USDC and accounts the principal leg.\n    function recordPayment(uint256 facilityId, address payer, uint256 usdcAmount, uint256 principal)\n        external\n        returns (uint256 receivedValue);\n\n    /// @notice Removes realized facility principal and consumes its corresponding impairment.\n    function recordPrincipalWritedown(uint256 facilityId, uint256 amount) external;\n\n    /// @notice Records an evidence-backed conservative mark without moving face principal or\n    ///         allocating the loss between capital layers.\n    function recognizePrincipalImpairment(uint256 facilityId, uint256 amount, bytes32 evidenceHash) external;\n\n    /// @notice Reverses a conservative mark, bounded by the amount previously recognized.\n    function releasePrincipalImpairment(uint256 facilityId, uint256 amount, bytes32 evidenceHash) external;\n\n    /// @notice Recorded idle custody expressed as 18-decimal USDfr value.\n    function idleReserve() external view returns (uint256);\n    /// @notice Recorded idle custody in native six-decimal USDC units.\n    function idleUSDC() external view returns (uint256);\n    /// @notice Aggregate deployed facility principal before conservative impairments.\n    function deployedPrincipal() external view returns (uint256);\n    /// @notice Aggregate evidence-backed conservative principal impairment.\n    function totalPrincipalImpairment() external view returns (uint256);\n    /// @notice Evidence-backed conservative impairment recorded for one facility.\n    function principalImpairmentOf(uint256 facilityId) external view returns (uint256);\n    /// @notice Recorded idle plus deployed principal, net of conservative impairments.\n    function totalBackingValue() external view returns (uint256);\n    /// @notice Outstanding receivable face deployed to one facility.\n    /// @dev Continuous accrual includes earned but unreceived cash and PIK interest.\n    function deployedTo(uint256 facilityId) external view returns (uint256);\n    /// @notice Canonical six-decimal USDC token held by the reserve.\n    function usdc() external view returns (address);\n    /// @notice Converts native six-decimal USDC units to 18-decimal protocol value.\n    function normalizeUSDC(uint256 amount) external pure returns (uint256);\n    /// @notice Converts exact 18-decimal protocol value to native USDC units.\n    function denormalizeUSDC(uint256 value) external pure returns (uint256);\n}\n"},{"file_path":"src/interfaces/IAccrualExposure.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {IContinuousAccrual} from \"./IContinuousAccrual.sol\";\n\n/// @title IAccrualExposure\n/// @notice Reserve-local unposted earned claims used by the collateral concentration book.\n/// @dev Values share the continuous Book's capped frontier and never scan facilities. A source\n///      must implement the complete continuous-accrual identity, snapshot and admission surface.\ninterface IAccrualExposure is IContinuousAccrual {\n    /// @notice Returns unposted normalized-18-decimal exposure for one aggregate identity.\n    /// @param kind Total=0, class=1, borrower=2, state=3.\n    /// @param identity Total uses zero; class uses bytes32(classId); borrower/state use their\n    ///      existing identity keys. A zero state represents no state tag and returns zero.\n    function accrualExposure(uint8 kind, bytes32 identity) external view returns (uint256);\n\n    /// @notice Additional future funded face already reserved beyond current effective exposure.\n    /// @dev Origination must preserve this numeric room, including while pending unfunded claims\n    ///      consume registry exposure. Concentration ratios continue to use current exposure.\n    function accrualReservedExposure() external view returns (uint256);\n\n    /// @notice Refuses an overlapping source operation without requiring its loan clock current.\n    /// @dev Repayment/loss decreases and governed recovery must not depend on keeper freshness.\n    function requireAccrualIdle() external view;\n}\n\n/// @title IAccrualExposureRegistry\n/// @notice Narrow registry continuation for physical posting of already earned exposure.\ninterface IAccrualExposureRegistry {\n    /// @notice Permanently binds the governed reserve that supplies virtual exposure.\n    function setAccrualReserve(address reserve) external;\n\n    /// @notice The permanent reserve, or zero while continuous exposure is disabled.\n    function accrualReserve() external view returns (address);\n\n    /// @notice Posts an already consumed reserve-local virtual claim into stored registry face.\n    /// @dev Only the bound reserve may call. It must first consume identical Book posting and\n    ///      write its native reserve face in the same protected operation. This is a neutral\n    ///      reclassification, bypassing origination limits while retaining the numeric cap.\n    function recordAccruedExposure(uint256 classId, bytes32 borrowerId, bytes32 stateId, uint256 amount) external;\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/UUPSUpgradeable.sol)\n\npragma solidity ^0.8.22;\n\nimport {IERC1822Proxiable} from \"@openzeppelin/contracts/interfaces/draft-IERC1822.sol\";\nimport {ERC1967Utils} from \"@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol\";\nimport {Initializable} from \"./Initializable.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 */\nabstract contract UUPSUpgradeable is Initializable, 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    function __UUPSUpgradeable_init() internal onlyInitializing {\n    }\n\n    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {\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 virtual 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"},{"file_path":"lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol","source_code":"// 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"},{"file_path":"lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol","source_code":"// 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"},{"file_path":"src/libraries/ReserveIncidentLib.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {ReserveManager} from \"../ReserveManager.sol\";\nimport {IReserveManager} from \"../interfaces/IReserveManager.sol\";\nimport {IMintRedeemController} from \"../interfaces/IMintRedeemController.sol\";\nimport {LossEventIds} from \"./LossEventIds.sol\";\nimport {ReserveStorageLib} from \"./ReserveStorageLib.sol\";\n\n/// @title ReserveIncidentLib\n/// @notice Native reserve incident bookkeeping with the original host storage and event identity.\n/// @dev ReserveManager retains its authority, reentrancy and accrual-idle guards. It also retains\n///      fee preparation and cascade calls. This helper locates no storage and calls no public\n///      library function; every operation runs through a linked call in the reserve context.\nlibrary ReserveIncidentLib {\n    /// @notice Opens the native legacy incident with its original unique event identity.\n    /// @dev Legacy bookkeeping is unavailable while an arm owns the custody incident lifecycle.\n    function openIncident(ReserveManager.ReserveStorage storage $, uint256 incidentNonce, bytes32 evidenceHash)\n        public\n        returns (uint256 incidentId)\n    {\n        if ($.activeReserveLossArmId != 0) {\n            revert IReserveManager.ReserveManager_ArmAlreadyActive($.activeReserveLossArmId);\n        }\n        if (incidentNonce >= LossEventIds.CUSTODY_EVENT_NAMESPACE_START) {\n            revert IReserveManager.ReserveManager_InvalidIncidentNonce(incidentNonce);\n        }\n        if ($.activeReserveLossIncidentId != 0) {\n            revert IReserveManager.ReserveManager_IncidentAlreadyActive($.activeReserveLossIncidentId);\n        }\n        incidentId = LossEventIds.custodyEventId(incidentNonce);\n        if ($.reserveLossIncidentUsed[incidentId]) {\n            revert IReserveManager.ReserveManager_IncidentAlreadyUsed(incidentId);\n        }\n        $.reserveLossIncidentUsed[incidentId] = true;\n        $.activeReserveLossIncidentId = incidentId;\n        $.activeReserveLossEvidenceHash = evidenceHash;\n        emit IReserveManager.ReserveLossIncidentOpened(incidentId, incidentNonce, evidenceHash);\n    }\n\n    /// @notice Closes only the currently active native incident.\n    /// @dev An arm-owned incident must close through the arm's checked finalization route.\n    function closeIncident(ReserveManager.ReserveStorage storage $, uint256 incidentId) public {\n        if ($.activeReserveLossArmId != 0) {\n            revert IReserveManager.ReserveManager_ArmAlreadyActive($.activeReserveLossArmId);\n        }\n        uint256 active = $.activeReserveLossIncidentId;\n        if (active == 0) revert IReserveManager.ReserveManager_NoActiveIncident();\n        if (incidentId != active) revert IReserveManager.ReserveManager_IncidentMismatch(active, incidentId);\n        $.activeReserveLossIncidentId = 0;\n        $.activeReserveLossEvidenceHash = bytes32(0);\n        emit IReserveManager.ReserveLossIncidentClosed(incidentId);\n    }\n\n    /// @notice Clears a recorded deficit only after the controller proves no deficit remains.\n    /// @dev The caller supplies the host namespace after its existing entry checks.\n    function resolveDeficit(ReserveManager.ReserveStorage storage $, bytes32 evidenceHash) public {\n        uint256 recordedDeficit = $.reserveDeficit;\n        if (recordedDeficit == 0) revert IReserveManager.ReserveManager_NoReserveDeficit();\n        if ($.activeReserveLossIncidentId != 0) {\n            revert IReserveManager.ReserveManager_IncidentAlreadyActive($.activeReserveLossIncidentId);\n        }\n        IMintRedeemController controller = $.lossController;\n        if (address(controller) == address(0)) revert IReserveManager.ReserveManager_InvalidLossController(address(0));\n        uint256 supply = controller.totalUSDfr();\n        uint256 backing = controller.backingValue();\n        uint256 observedDeficit = supply > backing ? supply - backing : 0;\n        if (observedDeficit != 0) {\n            revert IReserveManager.ReserveManager_DeficitStillExists(recordedDeficit, observedDeficit);\n        }\n        $.reserveDeficit = 0;\n        emit IReserveManager.ReserveDeficitResolved(recordedDeficit, evidenceHash);\n    }\n\n    /// @notice Arms one native custody incident under the host's guardian authority.\n    /// @dev The caller supplies the host namespace after its existing entry checks.\n    function arm(ReserveManager.ReserveStorage storage $, bytes32 evidenceHash)\n        public\n        returns (uint256 armId, uint256 incidentId)\n    {\n        if (!$.guardianReserveLossArmsEnabled) revert IReserveManager.ReserveManager_GuardianArmsDisabled();\n        if ($.activeReserveLossArmId != 0) {\n            revert IReserveManager.ReserveManager_ArmAlreadyActive($.activeReserveLossArmId);\n        }\n        if ($.activeReserveLossIncidentId != 0) {\n            revert IReserveManager.ReserveManager_IncidentAlreadyActive($.activeReserveLossIncidentId);\n        }\n        // Legacy incidents share the custody identity namespace. Skip identities they\n        // already consumed; the monotone cursor prevents rescanning those rows next time.\n        armId = $.nextReserveLossArmId;\n        do {\n            ++armId;\n            if (armId >= LossEventIds.CUSTODY_EVENT_NAMESPACE_START) {\n                revert IReserveManager.ReserveManager_ArmIdExhausted();\n            }\n            incidentId = LossEventIds.custodyEventId(armId);\n        } while ($.reserveLossIncidentUsed[incidentId]);\n        assert(LossEventIds.isCustodyEvent(incidentId));\n        $.nextReserveLossArmId = armId;\n        $.activeReserveLossArmId = armId;\n        $.activeReserveLossArmEvidenceHash = evidenceHash;\n        emit IReserveManager.ReserveLossArmed(armId, incidentId, evidenceHash);\n    }\n\n    /// @notice Cancels the exact arm only when its native interlock can be released.\n    /// @dev The caller supplies the host namespace after its existing entry checks.\n    function cancel(ReserveManager.ReserveStorage storage $, uint256 expectedArmId, bytes32 evidenceHash) public {\n        uint256 armId = _requireActiveArm($, expectedArmId);\n        _requireInterlockReleasable($);\n        _consumeArmAndDisable($);\n        emit IReserveManager.ReserveLossArmCancelled(armId, evidenceHash);\n    }\n\n    /// @notice Cancels a false alarm without releasing any independent credit impairment.\n    /// @dev The host retains governance authority and its operation-idle check.\n    function cancelUnratified(ReserveManager.ReserveStorage storage $, uint256 expectedArmId, bytes32 evidenceHash)\n        public\n    {\n        if (evidenceHash == bytes32(0)) revert IReserveManager.ReserveManager_ZeroEvidenceHash();\n        uint256 armId = _requireActiveArm($, expectedArmId);\n        if ($.reserveLossIncidentUsed[LossEventIds.custodyEventId(armId)]) {\n            revert IReserveManager.ReserveManager_ArmAlreadyRatified(armId);\n        }\n        if (\n            $.activeReserveLossIncidentId != 0 || $.recognizedSupplyReduction != 0 || $.reserveDeficit != 0\n                || address($.lossController).code.length == 0 || _liveShortfallUnits($) != 0\n        ) revert IReserveManager.ReserveManager_InterlockReleaseForbidden();\n        _consumeArmAndDisable($);\n        emit IReserveManager.UnratifiedReserveLossArmCancelled(armId, evidenceHash, $.totalPrincipalImpairment);\n    }\n\n    /// @notice Credits measured native recovery up to the original incident capacity.\n    /// @dev The caller supplies the host namespace after its existing entry checks.\n    function creditRecovery(ReserveManager.ReserveStorage storage $, uint256 armId, bytes32 evidenceHash)\n        public\n        returns (uint256 credited)\n    {\n        uint256 capacity = $.reserveLossRecoveryCapacityUnits[armId];\n        uint256 units = _availableRecoveredUSDC($, armId);\n        if (units == 0) revert IReserveManager.ReserveManager_NoRecoveredUSDC(armId);\n        $.idleUSDCUnits += units;\n        $.reserveLossRecoveryCapacityUnits[armId] = capacity - units;\n        credited = ReserveStorageLib.normalize(units);\n        emit IReserveManager.RecoveredIdleUSDCCredited(armId, units, credited, evidenceHash);\n    }\n\n    /// @notice Finalizes the exact fully settled arm and disables further guardian arms.\n    /// @dev The caller supplies the host namespace after its existing entry checks.\n    function finalize(ReserveManager.ReserveStorage storage $, uint256 expectedArmId, bytes32 evidenceHash) public {\n        uint256 armId = _requireActiveArm($, expectedArmId);\n        uint256 incidentId = LossEventIds.custodyEventId(armId);\n        uint256 active = $.activeReserveLossIncidentId;\n        if (active == 0) revert IReserveManager.ReserveManager_NoActiveIncident();\n        if (incidentId != active) revert IReserveManager.ReserveManager_IncidentMismatch(active, incidentId);\n        if ($.recognizedSupplyReduction != 0) {\n            revert IReserveManager.ReserveManager_RecognizedLossOutstanding($.recognizedSupplyReduction);\n        }\n        uint256 liveShortfall = _liveShortfallUnits($);\n        if (liveShortfall != 0) revert IReserveManager.ReserveManager_LiveShortfallExists(liveShortfall);\n        uint256 availableRecovery = _availableRecoveredUSDC($, armId);\n        if (availableRecovery != 0) {\n            revert IReserveManager.ReserveManager_RecoveredUSDCNotCredited(armId, availableRecovery);\n        }\n        IMintRedeemController controller = $.lossController;\n        if (address(controller) == address(0)) revert IReserveManager.ReserveManager_InvalidLossController(address(0));\n        uint256 supply = controller.totalUSDfr();\n        uint256 backing = controller.backingValue();\n        uint256 observedDeficit = supply > backing ? supply - backing : 0;\n        uint256 recordedDeficit = $.reserveDeficit;\n        if (observedDeficit != 0) {\n            revert IReserveManager.ReserveManager_DeficitStillExists(recordedDeficit, observedDeficit);\n        }\n        if (recordedDeficit != 0) {\n            $.reserveDeficit = 0;\n            emit IReserveManager.ReserveDeficitResolved(recordedDeficit, evidenceHash);\n        }\n        $.activeReserveLossIncidentId = 0;\n        $.activeReserveLossEvidenceHash = bytes32(0);\n        emit IReserveManager.ReserveLossIncidentClosed(incidentId);\n        _consumeArmAndDisable($);\n        emit IReserveManager.ReserveLossArmFinalized(armId, incidentId, evidenceHash);\n    }\n\n    function _requireInterlockReleasable(ReserveManager.ReserveStorage storage $) private view {\n        if (\n            $.activeReserveLossIncidentId != 0 || $.recognizedSupplyReduction != 0 || $.reserveDeficit != 0\n                || _liveShortfallUnits($) != 0\n        ) revert IReserveManager.ReserveManager_InterlockReleaseForbidden();\n        IMintRedeemController controller = $.lossController;\n        if (address(controller) == address(0) || controller.totalUSDfr() > controller.backingValue()) {\n            revert IReserveManager.ReserveManager_InterlockReleaseForbidden();\n        }\n    }\n\n    function _requireActiveArm(ReserveManager.ReserveStorage storage $, uint256 expectedArmId)\n        private\n        view\n        returns (uint256 armId)\n    {\n        armId = $.activeReserveLossArmId;\n        if (armId == 0) revert IReserveManager.ReserveManager_NoActiveArm();\n        if (expectedArmId != armId) revert IReserveManager.ReserveManager_ArmMismatch(armId, expectedArmId);\n    }\n\n    function _consumeArmAndDisable(ReserveManager.ReserveStorage storage $) private {\n        $.activeReserveLossArmId = 0;\n        $.activeReserveLossArmEvidenceHash = bytes32(0);\n        if ($.guardianReserveLossArmsEnabled) {\n            $.guardianReserveLossArmsEnabled = false;\n            emit IReserveManager.GuardianReserveLossArmsEnabled(false);\n        }\n    }\n\n    function _availableRecoveredUSDC(ReserveManager.ReserveStorage storage $, uint256 armId)\n        private\n        view\n        returns (uint256 units)\n    {\n        uint256 capacity = $.reserveLossRecoveryCapacityUnits[armId];\n        uint256 live = $.usdcToken.balanceOf(address(this));\n        uint256 recorded = $.idleUSDCUnits;\n        if (capacity == 0 || live <= recorded) return 0;\n        uint256 surplus = live - recorded;\n        return surplus < capacity ? surplus : capacity;\n    }\n\n    function _liveShortfallUnits(ReserveManager.ReserveStorage storage $) private view returns (uint256) {\n        uint256 live = $.usdcToken.balanceOf(address(this));\n        return $.idleUSDCUnits > live ? $.idleUSDCUnits - live : 0;\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol","source_code":"// 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"},{"file_path":"src/libraries/ReserveAccrualStorageLib.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {IContinuousAccrual} from \"../interfaces/IContinuousAccrual.sol\";\nimport {AccrualBook} from \"./AccrualBook.sol\";\nimport {AccrualLoans} from \"./AccrualLoans.sol\";\nimport {AccrualSchedule} from \"./AccrualSchedule.sol\";\n\n/// @title ReserveAccrualStorageLib\n/// @notice The reserve's own continuous-accrual namespace and storage-only backing helpers.\n/// @dev No external reads enter these helpers, including on BSC. Every financial clock is\n///      capped at the earliest unresolved event; only authenticated host transitions write it.\nlibrary ReserveAccrualStorageLib {\n    using AccrualSchedule for AccrualSchedule.Heap;\n\n    /// @notice Immutable identities copied from the funded bridge record.\n    struct Identity {\n        address asset;\n        uint256 classId;\n        bytes32 borrowerId;\n        bytes32 stateId;\n        uint256 reservedCeiling;\n        bool known;\n    }\n\n    /// @notice One exact burn within a reserve-derived contractual rounding correction.\n    /// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.\n    struct Rounding {\n        uint256 facilityId;\n        uint64 closureNonce;\n        address from;\n        uint256 amount;\n        bool active;\n        bool ready;\n    }\n\n    /// @notice The one-time native import session, with a bounded positive-face roster.\n    /// @dev LAYOUT-FROZEN: embedded storage; append future fields to State instead.\n    struct Migration {\n        uint64 cutoff;\n        uint32 expected;\n        uint32 imported;\n        uint16 feeBps;\n        bool active;\n        uint256 nonce;\n        uint256 originalFace;\n        uint256 importedOriginalFace;\n        bytes32 sessionKey;\n        uint256[] facilityIds;\n        mapping(uint256 facilityId => bytes32) frozenRecords;\n    }\n\n    /// @custom:storage-location erc7201:forestroad.storage.ContinuousAccrual\n    struct State {\n        AccrualLoans.State loans;\n        IContinuousAccrual.Modules modules;\n        mapping(uint256 facilityId => Identity) identities;\n        address feeRecipient;\n        uint256 reservedCeilings;\n        uint256 nonce;\n        IContinuousAccrual.Delivery delivery;\n        IContinuousAccrual.Snapshot deliverySnapshot;\n        bool enabled;\n        bool busy;\n        uint256 recordedFace;\n        Rounding rounding;\n        uint256 roundingUnabsorbed;\n        Migration migration;\n        // Irreversible feature latch appended after every historical field.\n        bool mixedInterestEnabled;\n    }\n\n    bytes32 private constant ACCRUAL_STORAGE_LOCATION =\n        0x2420c1d967401a6739c551e175fd4dfa8e9cd5ee804155e89721bed004930b00;\n\n    /// @notice The chain clock cannot be represented by the admitted schedule domain.\n    error ReserveAccrual_TimeOverflow();\n\n    /// @notice Accesses this reserve's independent accounting namespace.\n    function state() internal pure returns (State storage $) {\n        assembly {\n            $.slot := ACCRUAL_STORAGE_LOCATION\n        }\n    }\n\n    /// @notice Current checked schedule timestamp; no truncating casts are permitted.\n    function now64() internal view returns (uint64) {\n        if (block.timestamp > type(uint64).max) revert ReserveAccrual_TimeOverflow();\n        return uint64(block.timestamp);\n    }\n\n    /// @notice Portfolio clock frontier, including an unresolved endpoint at equality.\n    function frontier(State storage s) internal view returns (uint64 at) {\n        at = now64();\n        AccrualSchedule.Heap storage queue = s.loans.book.schedule;\n        if (queue.count() != 0) {\n            uint64 boundary = queue.peek().deadline;\n            if (boundary < at) at = boundary;\n        }\n    }\n\n    /// @notice Earned receivable not yet transferred to the native deployed-face ledger.\n    function unposted() internal view returns (uint256) {\n        State storage s = state();\n        if (!s.enabled) return 0;\n        AccrualBook.Book storage book = s.loans.book;\n        uint64 at = frontier(s);\n        return book.total.value + book.total.rate * (at - book.total.at) - book.posted;\n    }\n\n    /// @notice Facility's effective face increment; resolved historic entries return zero.\n    function facilityUnposted(uint256 facilityId) internal view returns (uint256) {\n        State storage s = state();\n        if (!s.enabled) return 0;\n        AccrualBook.Entry storage entry = s.loans.book.entries[facilityId];\n        if (!entry.known) return 0;\n        uint64 at = frontier(s);\n        return entry.clock.value + entry.clock.rate * (at - entry.clock.at) - entry.posted;\n    }\n\n    /// @notice Domain-separated, constant-time exposure keys for the immutable facility identities.\n    function keys(uint256 classId, bytes32 borrowerId, bytes32 stateId)\n        internal\n        pure\n        returns (bytes32[3] memory result)\n    {\n        result[0] = keccak256(abi.encode(uint8(1), classId));\n        result[1] = keccak256(abi.encode(uint8(2), borrowerId));\n        result[2] = keccak256(abi.encode(uint8(3), stateId));\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol","source_code":"// 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"},{"file_path":"src/libraries/ReserveAccrualCreditLib.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {ReserveManager} from \"../ReserveManager.sol\";\n\nimport {ClaimBridge} from \"../ClaimBridge.sol\";\nimport {ICollateralRegistry} from \"../interfaces/ICollateralRegistry.sol\";\nimport {IAccrualBridge, IAccrualRegistry, IAccrualRisk} from \"../interfaces/IAccrualLifecycle.sol\";\nimport {AccrualBook} from \"./AccrualBook.sol\";\nimport {AccrualLoans} from \"./AccrualLoans.sol\";\nimport {AccrualCeiling} from \"./AccrualCeiling.sol\";\nimport {ReserveAccrualLib} from \"./ReserveAccrualLib.sol\";\nimport {ReserveAccrualStorageLib} from \"./ReserveAccrualStorageLib.sol\";\nimport {ReserveStorageLib} from \"./ReserveStorageLib.sol\";\nimport {BridgeMixedInterestLib} from \"./BridgeMixedInterestLib.sol\";\n\n/// @title ReserveAccrualCreditLib\n/// @notice Authenticated fixed-rate loan lifecycle and native receivable posting in the reserve.\n/// @dev Public methods execute by delegatecall in the reserve. Its host supplies nonReentrant;\n///      these methods additionally authenticate the immutable module and close callback admission.\nlibrary ReserveAccrualCreditLib {\n    using AccrualBook for AccrualBook.Book;\n    using AccrualLoans for AccrualLoans.State;\n    using ReserveStorageLib for ReserveManager.ReserveStorage;\n\n    uint256 internal constant MAX_EXPOSURE = type(uint256).max / 10_000;\n\n    /// @notice This event is restricted to the immutable module that proves its economic facts.\n    error AccrualCredit_WrongCaller(address expected, address caller);\n    /// @notice The funded bridge and measured native receivable disagree.\n    error AccrualCredit_InvalidFunding(uint256 facilityId);\n    /// @notice The first release supports fixed Actual/360 and Actual/365 cash, and fixed Actual/360 PIK.\n    error AccrualCredit_UnsupportedTerms(uint256 facilityId);\n    /// @notice A known funded identifier cannot be registered or bound a second time.\n    error AccrualCredit_AlreadyKnown(uint256 facilityId);\n    /// @notice An event cannot address an omitted or unfunded receivable.\n    error AccrualCredit_Unknown(uint256 facilityId);\n    /// @notice All funded future ceilings and present pending exposure must fit the registry domain.\n    error AccrualCredit_ExposureCapacity();\n    /// @notice Past-due baseline installation requires existing growth to be posted first.\n    error AccrualCredit_UnpostedRisk(uint256 facilityId);\n    /// @notice The exposure key discriminator must be total=0, class=1, borrower=2 or state=3.\n    error AccrualCredit_InvalidExposureKind(uint8 kind);\n    /// @notice A measured receipt or native face failed the exact contractual accounting identity.\n    error AccrualCredit_ReceiptMismatch(uint256 facilityId);\n    /// @notice Native loss reductions cannot leave a running contractual clock or exceed stopped debt.\n    error AccrualCredit_InvalidWriteDown(uint256 facilityId);\n    /// @notice An accrued facility must use its authenticated lifecycle rather than a legacy upward/receipt setter.\n    error AccrualCredit_UseAccrualLifecycle(uint256 facilityId);\n\n    /// @notice Gates legacy funding ledger writes to the one bound waterfall before registration.\n    function requireUnregisteredFunding(uint256 id) internal view {\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        if (!s.enabled) return;\n        _caller(s.modules.waterfall);\n        if (s.identities[id].known) revert AccrualCredit_UseAccrualLifecycle(id);\n    }\n\n    /// @notice Legacy PIK/receipt ledgers cannot bypass continuous recognition after activation.\n    function requireLegacy(uint256 id) internal view {\n        if (ReserveAccrualStorageLib.state().enabled) revert AccrualCredit_UseAccrualLifecycle(id);\n    }\n\n    /// @notice Continuous recognition began on authenticated funded terms, from the funding block.\n    event AccruingLoanRegistered(\n        uint256 indexed facilityId,\n        address indexed asset,\n        uint256 indexed classId,\n        uint256 principal,\n        uint256 balanceCeiling,\n        uint16 rateBps,\n        uint32 yearSeconds,\n        uint64 fundedAt,\n        bool pik\n    );\n    event MixedAccruingLoanRegistered(\n        uint256 indexed facilityId,\n        uint16 cashRateBps,\n        uint16 pikRateBps,\n        uint64 nextCashPaymentDue,\n        uint64 nextPikCapitalization\n    );\n    /// @notice Existing earned interest moved from the virtual carrier to recorded face, without minting.\n    event AccruedLoanPosted(uint256 indexed facilityId, address indexed asset, uint256 amount, uint256 faceAfter);\n    /// @notice A keeper completed a chronological technical or signed contractual boundary.\n    event AccrualBoundaryProcessed(\n        uint256 indexed facilityId, uint64 indexed at, uint256 capitalized, uint64 nextDue, bool stopped\n    );\n    /// @notice The signed old curve closed before applying a forward amendment or declaration.\n    event AccrualLoanAligned(\n        uint256 indexed facilityId,\n        uint64 indexed closureNonce,\n        uint64 at,\n        uint256 positiveCorrection,\n        uint256 roundingLoss,\n        bool stopped\n    );\n    /// @notice Marked cohort membership changed without changing contractual interest entitlement.\n    event AccrualPastDueSet(uint256 indexed facilityId, bool marked);\n    /// @notice The remaining maximum future face reservation changed after a proved lifecycle event.\n    event AccrualCeilingReserved(uint256 indexed facilityId, uint256 previousCeiling, uint256 nextCeiling);\n\n    /// @notice Registers exactly the just-funded Active bridge facility; no caller supplies its terms.\n    function register(ReserveManager.ReserveStorage storage native, uint256 id) public {\n        ReserveAccrualStorageLib.State storage s = _fresh();\n        _caller(s.modules.waterfall);\n        if (s.identities[id].known) revert AccrualCredit_AlreadyKnown(id);\n        ClaimBridge.Facility memory f = ClaimBridge(s.modules.bridge).facility(id);\n        address asset = address(native.usdcToken);\n        if (f.state != ClaimBridge.LoanState.Active || asset == address(0) || native.deployed[id] != f.principal) {\n            revert AccrualCredit_InvalidFunding(id);\n        }\n        uint256 scale = ReserveStorageLib.USDC_SCALE;\n        uint64 at = ReserveAccrualStorageLib.now64();\n        bool mixed = s.mixedInterestEnabled && ClaimBridge(s.modules.bridge).isMixedInterest(id);\n        (AccrualLoans.Funding memory funded, uint16 cashRateBps, uint64 nextCashPaymentDue) =\n            _funding(s.modules.bridge, id, f, scale, at, mixed);\n        uint256 ceiling = ReserveAccrualLib.loanCeiling(\n            AccrualCeiling.Terms({\n                face: f.principal,\n                frozenBasis: f.principal,\n                scale: scale,\n                yearSeconds: funded.yearSeconds,\n                rateBps: f.interestRateBps,\n                at: at,\n                nextCapitalization: funded.nextPaymentDue,\n                paymentInterval: funded.paymentInterval,\n                maturity: f.maturity\n            }),\n            f.pik\n        );\n        _admitAdditional(s, ceiling - f.principal);\n        s.busy = true;\n        funded.balanceCeiling = ceiling;\n        if (mixed) s.loans.fundMixed(id, AccrualLoans.MixedFunding({pikTerms: funded, cashRateBps: cashRateBps}));\n        else s.loans.fund(id, funded);\n        s.identities[id] = ReserveAccrualStorageLib.Identity({\n            asset: asset,\n            classId: f.classId,\n            borrowerId: f.borrowerId,\n            stateId: f.stateId,\n            reservedCeiling: ceiling,\n            known: true\n        });\n        s.recordedFace += f.principal;\n        s.reservedCeilings += ceiling;\n        s.busy = false;\n        _emitRegistered(id, asset, f.classId, funded, f.interestRateBps);\n        if (mixed) {\n            emit MixedAccruingLoanRegistered(id, cashRateBps, funded.rateBps, nextCashPaymentDue, funded.nextPaymentDue);\n        }\n    }\n\n    /// @notice Bounded permissionless maintenance; does not mint or transfer every facility's face.\n    function checkpoint(ReserveManager.ReserveStorage storage native, uint256 maximum)\n        public\n        returns (uint256 processed, bool fresh)\n    {\n        ReserveAccrualLib.requireIdle();\n        ReserveAccrualStorageLib.State storage s = _enabled();\n        s.busy = true;\n        AccrualLoans.LifecycleWork[] memory work;\n        (work, processed, fresh) = s.loans.checkpoint(ReserveAccrualStorageLib.now64(), maximum);\n        for (uint256 i; i < processed; ++i) {\n            AccrualLoans.LifecycleWork memory item = work[i];\n            // A migrated legacy receipt can have advanced the native servicing date ahead\n            // of this coupon. Keep the bridge monotone while the canonical coupon clock catches up.\n            AccrualLoans.Loan storage loan = s.loans.loans[item.facilityId];\n            if (loan.mixed && item.previousDue != 0) {\n                IAccrualBridge(s.modules.bridge).setAccruedPaymentDue(item.facilityId, item.nextDue);\n            } else if (\n                item.nextDue != 0\n                    && item.nextDue > ClaimBridge(s.modules.bridge).facility(item.facilityId).nextPaymentDue\n            ) {\n                IAccrualBridge(s.modules.bridge).setAccruedPaymentDue(item.facilityId, item.nextDue);\n            }\n            if (item.stopped) {\n                _replaceCeiling(\n                    s,\n                    item.facilityId,\n                    native.deployed[item.facilityId] + ReserveAccrualStorageLib.facilityUnposted(item.facilityId)\n                );\n            }\n            emit AccrualBoundaryProcessed(item.facilityId, item.at, item.capitalized, item.nextDue, item.stopped);\n        }\n        s.busy = false;\n    }\n\n    /// @notice Neutral posting for a single facility before impairment or another native ledger act.\n    function post(ReserveManager.ReserveStorage storage native, uint256 id) public returns (uint256 amount) {\n        ReserveAccrualStorageLib.State storage s = _fresh();\n        _identity(s, id);\n        s.busy = true;\n        amount = s.loans.post(id, ReserveAccrualStorageLib.now64());\n        _post(native, s, id, amount);\n        s.busy = false;\n    }\n\n    /// @notice Constant-time earned additions to registry exposure; zero state has no jurisdiction book.\n    function exposure(uint8 kind, bytes32 key) public view returns (uint256 amount) {\n        if (kind > 3) revert AccrualCredit_InvalidExposureKind(kind);\n        if (kind == 0) return ReserveAccrualStorageLib.unposted();\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        if (!s.enabled || (kind == 3 && key == bytes32(0))) return 0;\n        return s.loans.book.groupUnposted(keccak256(abi.encode(kind, key)), ReserveAccrualStorageLib.now64());\n    }\n\n    /// @notice Future face already reserved, additional to the current registry's effective exposure.\n    function reservedExposure() public view returns (uint256 amount) {\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        if (!s.enabled) return 0;\n        uint256 effectiveFace = s.recordedFace + ReserveAccrualStorageLib.unposted();\n        return s.reservedCeilings > effectiveFace ? s.reservedCeilings - effectiveFace : 0;\n    }\n\n    /// @notice Growing marked-cohort face not yet included in the default manager's recorded mark.\n    function pastDue(uint256 classId) public view returns (uint256 amount) {\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        if (!s.enabled) return 0;\n        return s.loans.book.pastDueInterest(keccak256(abi.encode(uint8(1), classId)), ReserveAccrualStorageLib.now64());\n    }\n\n    function _emitRegistered(\n        uint256 id,\n        address asset,\n        uint256 classId,\n        AccrualLoans.Funding memory funded,\n        uint16 aggregateRateBps\n    ) private {\n        emit AccruingLoanRegistered(\n            id,\n            asset,\n            classId,\n            funded.principal,\n            funded.balanceCeiling,\n            aggregateRateBps,\n            uint32(funded.yearSeconds),\n            funded.fundedAt,\n            funded.pik\n        );\n    }\n\n    function _funding(\n        address bridgeAddress,\n        uint256 id,\n        ClaimBridge.Facility memory f,\n        uint256 scale,\n        uint64 at,\n        bool mixed\n    ) private view returns (AccrualLoans.Funding memory funded, uint16 cashRateBps, uint64 nextCashPaymentDue) {\n        uint16 accrualRate = f.interestRateBps;\n        uint64 nextCapitalization = f.nextPaymentDue;\n        uint64 capitalizationInterval = f.paymentInterval;\n        if (mixed) {\n            BridgeMixedInterestLib.InterestLegTerms memory legs = ClaimBridge(bridgeAddress).mixedInterestTerms(id);\n            cashRateBps = legs.cashRateBps;\n            accrualRate = legs.pikRateBps;\n            nextCapitalization = legs.nextPikCapitalization;\n            capitalizationInterval = legs.pikCapitalizationInterval;\n            nextCashPaymentDue = legs.nextCashPaymentDue;\n        }\n        funded = AccrualLoans.Funding({\n            principal: f.principal,\n            balanceCeiling: 0,\n            scale: scale,\n            yearSeconds: _year(id, f.rateType, f.dayCountConvention, f.pik),\n            rateBps: accrualRate,\n            fundedAt: at,\n            nextPaymentDue: nextCapitalization,\n            paymentInterval: capitalizationInterval,\n            maturity: f.maturity,\n            pik: f.pik,\n            keys: ReserveAccrualStorageLib.keys(f.classId, f.borrowerId, f.stateId),\n            frozenPikBasis: 0\n        });\n    }\n\n    function _post(\n        ReserveManager.ReserveStorage storage native,\n        ReserveAccrualStorageLib.State storage s,\n        uint256 id,\n        uint256 amount\n    ) private {\n        if (amount == 0) return;\n        ReserveAccrualStorageLib.Identity storage identity = s.identities[id];\n        native.deployed[id] += amount;\n        native.totalDeployedPrincipal += amount;\n        s.recordedFace += amount;\n        IAccrualRegistry(s.modules.registry).recordAccruedExposure(\n            identity.classId, identity.borrowerId, identity.stateId, amount\n        );\n        if (s.loans.book.entries[id].pastDue) IAccrualRisk(s.modules.defaultManager).onAccrualPosted(id, amount);\n        emit AccruedLoanPosted(id, identity.asset, amount, native.deployed[id]);\n    }\n\n    function _admitAdditional(ReserveAccrualStorageLib.State storage s, uint256 additional) private view {\n        uint256 effective = ICollateralRegistry(s.modules.registry).totalBookExposure();\n        uint256 future = reservedExposure();\n        if (\n            effective > MAX_EXPOSURE || future > MAX_EXPOSURE - effective\n                || additional > MAX_EXPOSURE - effective - future\n        ) {\n            revert AccrualCredit_ExposureCapacity();\n        }\n    }\n\n    function _replaceCeiling(ReserveAccrualStorageLib.State storage s, uint256 id, uint256 next) private {\n        uint256 previous = s.identities[id].reservedCeiling;\n        if (next > previous) _admitAdditional(s, next - previous);\n        s.reservedCeilings = s.reservedCeilings - previous + next;\n        s.identities[id].reservedCeiling = next;\n        emit AccrualCeilingReserved(id, previous, next);\n    }\n\n    function _year(uint256 id, ClaimBridge.RateType rate, ClaimBridge.DayCountConvention convention, bool pik)\n        private\n        pure\n        returns (uint32)\n    {\n        if (rate != ClaimBridge.RateType.Fixed) revert AccrualCredit_UnsupportedTerms(id);\n        if (convention == ClaimBridge.DayCountConvention.Actual360) return uint32(360 days);\n        if (!pik && convention == ClaimBridge.DayCountConvention.Actual365) return uint32(365 days);\n        revert AccrualCredit_UnsupportedTerms(id);\n    }\n\n    function _fresh() private view returns (ReserveAccrualStorageLib.State storage s) {\n        ReserveAccrualLib.requireFresh();\n        return _enabled();\n    }\n\n    function _enabled() private view returns (ReserveAccrualStorageLib.State storage s) {\n        s = ReserveAccrualStorageLib.state();\n        if (!s.enabled) revert ReserveAccrualLib.ReserveAccrual_NotEnabled();\n    }\n\n    function _identity(ReserveAccrualStorageLib.State storage s, uint256 id) private view {\n        if (!s.identities[id].known) revert AccrualCredit_Unknown(id);\n    }\n\n    function _caller(address expected) private view {\n        if (msg.sender != expected) revert AccrualCredit_WrongCaller(expected, msg.sender);\n    }\n}\n"},{"file_path":"src/libraries/ReserveCascadeLib.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {ReserveManager} from \"../ReserveManager.sol\";\nimport {IReserveManager} from \"../interfaces/IReserveManager.sol\";\nimport {IReserveLossAbsorber} from \"../interfaces/IReserveLossAbsorber.sol\";\nimport {IMintRedeemController} from \"../interfaces/IMintRedeemController.sol\";\nimport {ICuratorModule} from \"../interfaces/ICuratorModule.sol\";\nimport {ICascadeBackstop} from \"../interfaces/ICascadeBackstop.sol\";\nimport {LossEventIds} from \"./LossEventIds.sol\";\n\n/// @title ReserveCascadeLib\n/// @notice Ethereum's native custody-loss accounting, separated to leave room for continuous accrual.\n/// @dev No storage is declared or located here. ReserveManager passes its original live namespace\n///      pointer and retains all external authorization, arm/evidence and reentrancy checks. The\n///      curator -> sGROVE -> senior order and the existing surplus/residual accounting are retained.\nlibrary ReserveCascadeLib {\n    /// @notice Records a custody loss against the exact native reserve state.\n    /// @dev The host authenticates the arm, evidence, loss approval and reentrancy guard.\n    function recognize(ReserveManager.ReserveStorage storage $, uint256 nativeUnits, uint256 backingReduction) public {\n        IMintRedeemController controller = $.lossController;\n        if (address(controller) == address(0)) revert IReserveManager.ReserveManager_InvalidLossController(address(0));\n        uint256 supplyBefore = controller.totalUSDfr();\n        uint256 backingBefore = controller.backingValue();\n        if (backingReduction > backingBefore) {\n            revert IReserveManager.ReserveManager_LossAllocationMismatch(0, 0, backingReduction, backingBefore);\n        }\n\n        uint256 surplusBefore = backingBefore > supplyBefore ? backingBefore - supplyBefore : 0;\n        uint256 surplusAbsorbed = backingReduction < surplusBefore ? backingReduction : surplusBefore;\n        uint256 supplyReductionRequired = backingReduction - surplusAbsorbed;\n        _retireCustodyPrepayment($, $.activeReserveLossIncidentId, surplusBefore, surplusAbsorbed);\n\n        // Recognition lowers backing first. Every subsequent burn is checked as a precise,\n        // non-worsening reduction of the now-visible deficit by MintRedeemController.\n        $.idleUSDCUnits -= nativeUnits;\n        emit IReserveManager.ReserveLossRecognized(\n            $.activeReserveLossIncidentId, backingReduction, surplusAbsorbed, supplyReductionRequired\n        );\n\n        if (supplyReductionRequired == 0) {\n            IReserveLossAbsorber.ReserveLossAllocation memory allocation;\n            allocation.surplusAbsorbed = surplusAbsorbed;\n            _emitReserveLossAllocated($.activeReserveLossIncidentId, backingReduction, allocation);\n            return;\n        }\n        $.recognizedBackingReduction += backingReduction;\n        $.recognizedSurplusAbsorbed += surplusAbsorbed;\n        $.recognizedSupplyReduction += supplyReductionRequired;\n    }\n\n    /// @dev Retires only credit whose surplus backing this custody loss consumed. Surplus\n    ///      beyond the prepaid balance absorbs loss first. Retired credit cannot offset a later\n    ///      facility loss after the capital supporting it has already been spent.\n    function _retireCustodyPrepayment(\n        ReserveManager.ReserveStorage storage $,\n        uint256 incidentId,\n        uint256 surplusBefore,\n        uint256 surplusAbsorbed\n    ) private {\n        uint256 prepaid = $.exitPrepaidAbsorption;\n        uint256 freeSurplus = surplusBefore > prepaid ? surplusBefore - prepaid : 0;\n        if (surplusAbsorbed <= freeSurplus) return;\n        uint256 used = surplusAbsorbed - freeSurplus;\n        uint256 outstanding = prepaid - used;\n        $.exitPrepaidAbsorption = outstanding;\n        emit IReserveManager.ExitPrepaymentAbsorbedByCustody(incidentId, used, outstanding);\n    }\n\n    /// @notice Allocates the recognized loss through curator, sGROVE and senior assets.\n    /// @dev Executes in the reserve context; every transfer and supply/backing delta remains proved.\n    function absorb(ReserveManager.ReserveStorage storage $, uint256 incidentId) public {\n        if (!LossEventIds.isCustodyEvent(incidentId)) {\n            revert IReserveManager.ReserveManager_InvalidReserveLossIncident(incidentId);\n        }\n        uint256 active = $.activeReserveLossIncidentId;\n        if (active == 0) revert IReserveManager.ReserveManager_NoActiveIncident();\n        if (incidentId != active) revert IReserveManager.ReserveManager_IncidentMismatch(active, incidentId);\n\n        uint256 requiredSupplyReduction = $.recognizedSupplyReduction;\n        if (requiredSupplyReduction == 0) revert IReserveManager.ReserveManager_NoRecognizedReserveLoss();\n        IMintRedeemController controller = $.lossController;\n        if (\n            address($.lossCurator) == address(0) || address($.lossBackstop) == address(0)\n                || address($.lossVault) == address(0) || address($.lossUSDfr) == address(0)\n        ) revert IReserveManager.ReserveManager_InvalidLossAbsorber(address(0));\n        if (address(controller) == address(0)) revert IReserveManager.ReserveManager_InvalidLossController(address(0));\n\n        $.lossVault.accrueFees();\n        uint256 supplyBefore = controller.totalUSDfr();\n        // Recognition has already lowered backing by `recognizedBackingReduction`. Reconstruct\n        // the pre-loss level so the standing valuation hole and any previously latched cascade\n        // residual are carried through the new delta rather than charged or latched twice.\n        uint256 backingAfterRecognition = controller.backingValue();\n        uint256 backingBeforeLoss = backingAfterRecognition + $.recognizedBackingReduction;\n        uint256 deficitBefore = supplyBefore > backingBeforeLoss ? supplyBefore - backingBeforeLoss : 0;\n        IReserveLossAbsorber.ReserveLossAllocation memory allocation;\n        uint256 residual;\n        (allocation.curatorAbsorbed, allocation.backstopCovered, residual) =\n            _drawJuniorReserveLoss($.lossCurator, $.lossBackstop, $.lossUSDfr, incidentId, requiredSupplyReduction);\n\n        uint256 juniorBurn = allocation.curatorAbsorbed + allocation.backstopCovered;\n        if (juniorBurn != 0) controller.burnLoss(address(this), juniorBurn);\n\n        if (residual != 0) {\n            uint256 vaultAssets = $.lossVault.totalAssets();\n            allocation.seniorBurned = residual < vaultAssets ? residual : vaultAssets;\n            if (allocation.seniorBurned != 0) {\n                controller.burnLoss(address($.lossVault), allocation.seniorBurned);\n                residual -= allocation.seniorBurned;\n            }\n        }\n        allocation.residualDeficit = residual;\n        allocation.surplusAbsorbed = $.recognizedSurplusAbsorbed;\n\n        _finalizeReserveLoss($, incidentId, requiredSupplyReduction, supplyBefore, deficitBefore, allocation);\n    }\n\n    function _finalizeReserveLoss(\n        ReserveManager.ReserveStorage storage $,\n        uint256 incidentId,\n        uint256 requiredSupplyReduction,\n        uint256 supplyBefore,\n        uint256 deficitBefore,\n        IReserveLossAbsorber.ReserveLossAllocation memory allocation\n    ) private {\n        uint256 observedDeficit =\n            _verifyReserveLoss($, requiredSupplyReduction, supplyBefore, deficitBefore, allocation);\n        uint256 backingReduction = $.recognizedBackingReduction;\n        $.recognizedBackingReduction = 0;\n        $.recognizedSurplusAbsorbed = 0;\n        $.recognizedSupplyReduction = 0;\n\n        // Only the portion of the pre-loss hole that was already a cascade residual is carried\n        // into the latch. A standing valuation mark is an output/price constraint, not a new\n        // custody shortfall; the current loss has already been offered unconditionally above.\n        uint256 previousDeficit = $.reserveDeficit;\n        uint256 carriedValuationDeficit = deficitBefore > previousDeficit ? deficitBefore - previousDeficit : 0;\n        uint256 nextDeficit = observedDeficit - carriedValuationDeficit;\n        if (nextDeficit != previousDeficit) {\n            $.reserveDeficit = nextDeficit;\n            emit IReserveManager.ReserveDeficitUpdated(incidentId, previousDeficit, nextDeficit);\n        }\n        _emitReserveLossAllocated(incidentId, backingReduction, allocation);\n    }\n\n    function _verifyReserveLoss(\n        ReserveManager.ReserveStorage storage $,\n        uint256 requiredSupplyReduction,\n        uint256 supplyBefore,\n        uint256 deficitBefore,\n        IReserveLossAbsorber.ReserveLossAllocation memory allocation\n    ) private view returns (uint256 observedDeficit) {\n        IMintRedeemController controller = $.lossController;\n        uint256 supplyAfter = controller.totalUSDfr();\n        uint256 reportedBurn = allocation.curatorAbsorbed + allocation.backstopCovered + allocation.seniorBurned;\n        uint256 observedBurn = supplyAfter > supplyBefore ? 0 : supplyBefore - supplyAfter;\n        if (reportedBurn > requiredSupplyReduction || observedBurn != reportedBurn) {\n            revert IReserveManager.ReserveManager_LossAbsorberContractViolated(reportedBurn, observedBurn);\n        }\n        uint256 expectedAccounted = $.recognizedBackingReduction - $.recognizedSurplusAbsorbed;\n        uint256 reportedAccounted = reportedBurn + allocation.residualDeficit;\n        if (expectedAccounted != requiredSupplyReduction || reportedAccounted != expectedAccounted) {\n            revert IReserveManager.ReserveManager_LossAllocationMismatch(\n                $.recognizedSurplusAbsorbed, allocation.surplusAbsorbed, expectedAccounted, reportedAccounted\n            );\n        }\n        uint256 backingAfter = controller.backingValue();\n        observedDeficit = supplyAfter > backingAfter ? supplyAfter - backingAfter : 0;\n        uint256 expectedDeficit = deficitBefore + requiredSupplyReduction;\n        expectedDeficit = expectedDeficit > reportedBurn ? expectedDeficit - reportedBurn : 0;\n        if (observedDeficit != expectedDeficit) {\n            revert IReserveManager.ReserveManager_PostLossDeficitMismatch(expectedDeficit, observedDeficit);\n        }\n    }\n\n    function _drawJuniorReserveLoss(\n        ICuratorModule curator,\n        ICascadeBackstop backstop,\n        IERC20 usdfr,\n        uint256 incidentId,\n        uint256 requiredSupplyReduction\n    ) private returns (uint256 curatorAbsorbed, uint256 backstopCovered, uint256 residual) {\n        uint256 balanceBefore = usdfr.balanceOf(address(this));\n        (curatorAbsorbed, residual) = curator.absorbGlobalLoss(requiredSupplyReduction);\n        if (curatorAbsorbed > requiredSupplyReduction || residual != requiredSupplyReduction - curatorAbsorbed) {\n            revert IReserveManager.ReserveManager_LossAllocationMismatch(\n                0, 0, requiredSupplyReduction, curatorAbsorbed + residual\n            );\n        }\n        uint256 balanceAfter = usdfr.balanceOf(address(this));\n        uint256 received = balanceAfter < balanceBefore ? 0 : balanceAfter - balanceBefore;\n        if (received != curatorAbsorbed) {\n            revert IReserveManager.ReserveManager_LossAbsorberContractViolated(curatorAbsorbed, received);\n        }\n\n        if (residual != 0) {\n            balanceBefore = balanceAfter;\n            backstopCovered = backstop.coverShortfall(incidentId, residual);\n            balanceAfter = usdfr.balanceOf(address(this));\n            received = balanceAfter < balanceBefore ? 0 : balanceAfter - balanceBefore;\n            if (backstopCovered > residual || received != backstopCovered) {\n                revert IReserveManager.ReserveManager_LossAbsorberContractViolated(backstopCovered, received);\n            }\n            residual -= backstopCovered;\n        }\n    }\n\n    function _emitReserveLossAllocated(\n        uint256 incidentId,\n        uint256 backingReduction,\n        IReserveLossAbsorber.ReserveLossAllocation memory allocation\n    ) private {\n        emit IReserveManager.ReserveLossAllocated(\n            incidentId,\n            backingReduction,\n            allocation.surplusAbsorbed,\n            allocation.curatorAbsorbed,\n            allocation.backstopCovered,\n            allocation.seniorBurned,\n            allocation.residualDeficit\n        );\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol","source_code":"// 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"},{"file_path":"src/interfaces/IWaterfallEngine.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\n/// @title IWaterfallEngine — repayment routing (brief Part 5 §9)\n/// @notice Routes every attested repayment with exact conservation (CLAUDE.md §1.3):\n///         principal returns to reserves (backing composition shifts, exposure falls);\n///         interest splits protocol fee → sUSDfr vault yield.\n///         Senior (`sUSDfr`) is never subordinated to junior (curator): curator capital\n///         is only released as exposure falls, never paid from repayments ahead of the\n///         vault. Also owns facility funding (deployment is distribution's inverse).\ninterface IWaterfallEngine {\n    struct Payment {\n        uint256 tokenId;\n        bytes32 paymentId;\n        address payer;\n        uint256 interest;\n        uint256 principal;\n        uint64 nextPaymentDue;\n    }\n    // ── Events ───────────────────────────────────────────────────────────\n\n    event Funded(uint256 indexed tokenId, address indexed recipient, uint256 principal);\n\n    /// @notice One contractual interval of PIK interest joined a facility's deployed principal.\n    /// @dev No cash moved. `rateBps` is the SNAPSHOT the period ran at rather than the facility's\n    ///      live rate, which is what makes amendments forward-only.\n    event PikInterestCapitalized(\n        uint256 indexed tokenId,\n        uint256 indexed classId,\n        uint256 amount,\n        uint256 balanceAfter,\n        uint64 periodEnd,\n        uint16 rateBps\n    );\n    /// @notice OID origination fee (ADR-0019): the borrower netted `principal - fee`;\n    ///         the fee's stables stay in the treasury and the fee mints to the\n    ///         protocol fee recipient against them.\n    /// @dev AUDIT FIX (R18): `fee` is what the BORROWER WAS CHARGED and is capitalised into their\n    ///      principal in full. It is no longer necessarily what was MINTED to the fee recipient —\n    ///      see `OriginationFeeWithheldForBackingRepair`, which reports any withheld part, so the\n    ///      split is reconstructable from logs alone (CLAUDE.md §3.1).\n    event OriginationFeeCharged(uint256 indexed tokenId, uint256 indexed classId, uint256 fee);\n    /// @notice AUDIT FIX (R18). Part of an ORIGINATION fee was NOT minted to the fee recipient: the\n    ///         value stayed in the treasury as unencumbered backing. The origination-leg twin of\n    ///         `InterestWithheldForBackingRepair`, and emitted for the same three reasons the\n    ///         headroom can be short — a standing deficit, an unreconciled custody shortfall, or\n    ///         `MintRedeemController.seniorSubParShortfall()` — plus a controller or USDfr pause.\n    /// @dev Before R18 this mint was unclamped and simply REVERTED in those states, which made a\n    ///      crystallised senior haircut a freeze on all fee-bearing origination and blocked the only\n    ///      cure the retention names (see `MintRedeemController.seniorSubParShortfall`). Emitted\n    ///      only when something was withheld, so its absence is the normal case.\n    /// @param tokenId The facility being funded.\n    /// @param withheld 18-decimal USD of fee retained as backing rather than minted.\n    /// @param deficitRemaining `MintRedeemController.recognizedDeficit()` measured at this point.\n    ///        AUDIT FIX (SWEEP-2 S2-F2) — READ THIS BEFORE TREATING IT AS \"HOW BIG IS THE HOLE\".\n    ///        IT IS ZERO IN EVERY STATE THIS CLAMP EXISTS FOR. R18 added the clamp for the\n    ///        `seniorSubParShortfall` RETENTION state, and `mintYield`'s own NatSpec says that\n    ///        state \"INCLUDES states the protocol publishes as fully backed and even OVER-backed:\n    ///        `backingInvariantHolds()` TRUE, `backingDeficit()` and `recognizedDeficit()` both\n    ///        zero.\" MEASURED: a 10,000e18 origination fee withheld against\n    ///        `deficitRemaining == 0`. The same is true of the two PAUSE terms and of ADR-0034\n    ///        Y-bis's `exitPrepaidAbsorption()`. The field is retained rather than changed because\n    ///        the on-chain register must be reconstructable from events and this one has been\n    ///        emitted since R17; treat it as \"recognised deficit at this point\", NOT as\n    ///        \"the reason for the withholding\". `withheld` is the reliable field.\n    event OriginationFeeWithheldForBackingRepair(uint256 indexed tokenId, uint256 withheld, uint256 deficitRemaining);\n    /// @notice AUDIT FIX (R16-M5). Part of an interest receipt was NOT distributed as yield: the\n    ///         cash stayed in the reserve to repair a standing backing deficit. Emitted only in\n    ///         the sub-par state, so its absence is the normal case.\n    /// @param withheld 18-decimal USD of interest retained as backing rather than minted.\n    /// @param deficitRemaining AUDIT FIX (SWEEP-2 S2-F2) — THIS LINE NAMED THE WRONG FUNCTION.\n    ///        It documented `MintRedeemController.backingDeficit()`; the code has emitted\n    ///        `recognizedDeficit()` since R17, which is the RECOGNITION-AWARE measure (it nets the\n    ///        R4-01 custody shortfall) and differs from `backingDeficit()` in exactly the state R17\n    ///        added it for. MEASURED in that state: `backingDeficit() == 0` while\n    ///        `recognizedDeficit() == 8,000e18` and the event carried 7,000e18.\n    ///        AND IT IS ZERO IN FOUR OF THE FIVE STATES THAT CAUSE A WITHHOLDING: R17's\n    ///        `seniorSubParShortfall`, R18's two pause terms and ADR-0034 Y-bis's\n    ///        `exitPrepaidAbsorption()` all clamp `mintableHeadroom()` without moving\n    ///        `recognizedDeficit()`. MEASURED: a paused controller withheld a 40,000e18 interest\n    ///        receipt in full and published `deficitRemaining == 0` on a book where\n    ///        `backingInvariantHolds()` was TRUE. Treat it as \"recognised deficit at this point\",\n    ///        NOT as \"how much of the hole is still open\"; `withheld` is the reliable field.\n    event InterestWithheldForBackingRepair(uint256 withheld, uint256 deficitRemaining);\n    /// @notice AUDIT FIX (ADV-1). Part of the INTEREST-LEG PROTOCOL FEE was NOT minted to the fee\n    ///         recipient: Forest Road may not take a performance fee out of a senior shortfall that\n    ///         junior capital has already declined to absorb. The withheld value is never minted, so\n    ///         it stays in the reserve as unencumbered backing exactly as\n    ///         `InterestWithheldForBackingRepair` describes — but it is sized off a CREDIT-layer\n    ///         quantity (`DefaultManager.pendingSeniorImpairment()`) that\n    ///         `MintRedeemController.mintableHeadroom()` is structurally blind to, so the two\n    ///         withholdings are DISTINCT and are reported separately.\n    /// @dev Emitted only when something was withheld, so its absence is the normal case. Together\n    ///      with `Distributed` (whose `fee` is the NET minted amount) the gross fee is\n    ///      reconstructable from logs alone as `fee + withheld` (CLAUDE.md §3.1). DO NOT \"simplify\"\n    ///      this into `InterestWithheldForBackingRepair`: that event's `deficitRemaining` is the\n    ///      RECOGNISED deficit, which is ZERO in exactly the state this event fires in, and an\n    ///      indexer could not tell the two causes apart.\n    /// @param withheld 18-decimal USD of protocol fee retained as backing rather than minted.\n    /// @param seniorImpairment `DefaultManager.pendingSeniorImpairment()` measured at this point,\n    ///        i.e. the declared/past-due principal that curator first-loss and the sGROVE backstop\n    ///        will NOT absorb and which therefore lands on `sUSDfr` or beyond.\n    event ProtocolFeeWithheldForSeniorImpairment(uint256 withheld, uint256 seniorImpairment);\n    event OriginationFeeSet(uint256 indexed classId, uint16 feeBps);\n    /// @notice Exact USDC receipt and its accounting split.\n    /// @dev `fee` IS THE NET MINTED AMOUNT, NOT THE GROSS SKIM (AUDIT FIX ADV-1). It was already\n    ///      net of the R16-M5 headroom clamp; it is now also net of the ADV-1 senior-impairment\n    ///      withholding. `interest == fee + toVault` therefore holds only in the unimpaired,\n    ///      full-headroom state; in general `interest - fee - toVault` is the total retained as\n    ///      backing, split across `InterestWithheldForBackingRepair` and\n    ///      `ProtocolFeeWithheldForSeniorImpairment`.\n    event Distributed(\n        uint256 indexed tokenId,\n        bytes32 indexed paymentId,\n        address indexed payer,\n        uint256 interest,\n        uint256 principal,\n        uint256 fee,\n        uint256 toVault\n    );\n    event ProtocolFeeSet(uint16 feeBps);\n    event FeeRecipientSet(address indexed recipient);\n\n    // ── Errors ───────────────────────────────────────────────────────────\n    error Waterfall_ZeroAddress();\n    error Waterfall_ZeroAmount();\n    error Waterfall_BadFee(uint16 feeBps);\n    error Waterfall_UnknownClass(uint256 classId);\n    error Waterfall_NotFundable(uint256 tokenId);\n    error Waterfall_NotDistributable(uint256 tokenId);\n    error Waterfall_PrincipalMismatch(uint256 tokenId, uint256 expected, uint256 got);\n    /// @notice No current PaymentReceived attestation commits to the exact receipt.\n    error Waterfall_PaymentNotAttested(uint256 tokenId);\n    /// @notice A distribution would leave USDfr supply above backing (the returning\n    ///         principal stables did not actually arrive in the treasury this tx).\n    error Waterfall_BackingWouldBreak(uint256 tokenId);\n    error Waterfall_PrincipalExceedsOutstanding(uint256 tokenId, uint256 principal, uint256 outstanding);\n\n    // ── PIK capitalisation (docs/SPEC_INTEREST_ACCRUAL.md) ─────────────────\n    /// @notice The facility does not contractually capitalise interest. Cash-pay loans pay their\n    ///         interest through `distribute`; capitalising it too would recognise it twice.\n    error Waterfall_PikNotDesignated(uint256 tokenId);\n\n    /// @notice A PIK facility was handed a payment carrying a cash INTEREST leg.\n    /// @dev THE DESIGNATION GATE USED TO BE ONE-DIRECTIONAL. It stopped a cash-pay loan\n    ///      capitalising, and nothing stopped a PIK loan paying cash: `distribute` never read\n    ///      `f.pik`. The leg routed to the senior vault and advanced `nextPaymentDue` while\n    ///      `pikCursor` stayed put, so the permissionless crank still saw the period unsettled\n    ///      and capitalised it, growing `deployed` by interest already paid and minting it to\n    ///      the vault a second time. Under a PIK facility the capitalisation IS the payment and\n    ///      the interest returns as `payment.principal` (spec decision 7), so a non-zero\n    ///      interest leg here is always a servicing error.\n    error Waterfall_PikCashInterestNotPermitted(uint256 tokenId);\n    /// @notice PIK is restricted to Receivable classes, because the past-due distress guard only\n    ///         works there. A marked-to-market class has no reachable distress predicate.\n    error Waterfall_PikClassNotReceivable(uint256 tokenId, uint256 classId);\n    /// @notice The facility is not performing, so it may not capitalise interest.\n    error Waterfall_PikNotPerforming(uint256 tokenId, uint8 state);\n    /// @notice The facility is flagged past due. Past due is a `DefaultManager` flag rather than a\n    ///         `ClaimBridge` state, so this is a separate check.\n    error Waterfall_PikPastDue(uint256 tokenId);\n    /// @notice Only Fixed-rate facilities capitalise; a Variable rate has no attested index.\n    error Waterfall_PikRateTypeUnsupported(uint256 tokenId);\n    /// @notice Only Actual/360 is implemented; Thirty360 needs the exact civil-date count.\n    error Waterfall_PikDayCountUnsupported(uint256 tokenId);\n    /// @notice The facility has never been funded, so its PIK clock has not started. This is also\n    ///         the MIGRATION guard for facilities that predate the feature.\n    error Waterfall_PikNotFunded(uint256 tokenId);\n    /// @notice The next contractual interval has not elapsed yet.\n    error Waterfall_PikIntervalNotElapsed(uint256 tokenId, uint64 dueAt);\n    /// @notice The interval would settle past maturity; the balance is due, not compounding.\n    error Waterfall_PikPastMaturity(uint256 tokenId, uint64 maturity);\n    /// @notice The facility has no outstanding principal to capitalise against.\n    error Waterfall_PikNothingOutstanding(uint256 tokenId);\n    /// @notice Record the elapsed PIK coupon before closing a performing legacy loan.\n    error Waterfall_PikSettlementRequired(uint256 tokenId, uint64 dueAt);\n    /// @notice Deprecated selector retained for decoding earlier implementations; no longer emitted.\n    error Waterfall_PikBalanceCapReached(uint256 tokenId, uint256 outstanding, uint256 ceiling);\n    /// @notice Full interest or the next frozen basis cannot fit the registry's numerical domain.\n    error Waterfall_PikExposureCapacity(uint256 tokenId);\n    /// @notice The interval's interest rounds to nothing on the USDC grid.\n    error Waterfall_PikBelowScaleGrid(uint256 tokenId, uint256 scale);\n    /// @notice A PIK facility cannot be funded so late in its first period that the first\n    ///         capitalisation would round to nothing on the USDC grid.\n    /// @dev Added 2026-09-10 with the funding-anchored first period. `checkFundable` already refuses\n    ///      funding at or after `nextPaymentDue`, so the window is at least one second; what it does\n    ///      not guarantee is that the window is long enough for the interest to be expressible. Since\n    ///      `nextPaymentDue` advances only inside `capitalizePik`, a facility funded too late in its\n    ///      first period would be frozen for life by its own first crank, so this fails closed BEFORE\n    ///      any value moves. The remedy is the operator's: amend the schedule, or fund sooner.\n    /// @param tokenId The facility.\n    /// @param window Seconds remaining in the first period at the funding block.\n    /// @param scale The smallest amount the facility's currency can express, in 18-dec terms.\n    error Waterfall_PikFirstPeriodBelowScaleGrid(uint256 tokenId, uint256 window, uint256 scale);\n\n    // ── Servicing paths (SERVICER_ROLE; attested facts per ADR-0007) ─────\n    /// @notice Funds a Pending facility: deploys exactly its principal from idle\n    ///         reserves to `recipient` (escrow/borrower account) and activates it.\n    function fund(uint256 tokenId, uint256 usdcAmount) external;\n\n    /// @notice Distributes an attested repayment receipt. The corresponding stables\n    ///         MUST already sit in the treasury (same transaction); the backing\n    ///         invariant assertion inside `mintYield` enforces this for the interest\n    ///         leg. Auto-transitions: first partial principal → Amortizing; outstanding\n    ///         reaching zero → Repaid. Callable while Defaulted/Accelerated to route\n    ///         recovery proceeds.\n    function distribute(Payment calldata payment) external;\n\n    // ── Governance ───────────────────────────────────────────────────────\n    /// @notice Sets the protocol fee on interest (bps). Timelocked governance only.\n    function setProtocolFee(uint16 feeBps) external;\n\n    /// @notice Sets a class's origination fee (bps of principal, hard-capped at\n    ///         Config.MAX_ORIGINATION_FEE_BPS; zero = no fee). Timelocked governance.\n    function setOriginationFee(uint256 classId, uint16 feeBps) external;\n\n    /// @notice Sets the protocol fee recipient. Timelocked governance only.\n    function setFeeRecipient(address recipient) external;\n\n    // ── Views ────────────────────────────────────────────────────────────\n    /// @notice Current protocol fee on distributed interest (bps).\n    function protocolFeeBps() external view returns (uint16);\n\n    /// @notice Current origination fee for a class (bps of principal).\n    function originationFeeBps(uint256 classId) external view returns (uint16);\n\n    /// @notice Current protocol fee recipient.\n    function feeRecipient() external view returns (address);\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol","source_code":"// 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"},{"file_path":"src/interfaces/IAccrualMigration.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\n/// @notice One governed, attested transition from recorded legacy debt to continuous accrual.\ninterface IAccrualMigration {\n    /// @notice Contractual debt and its original current-period cursor at the migration cutoff.\n    /// @dev Terms, asset, identity and recorded face come from the frozen native records.\n    ///      nextCapitalization is zero for cash or for PIK with no further signed capitalization.\n    struct Opening {\n        uint256 facilityId;\n        uint256 principal;\n        uint256 interest;\n        uint256 frozenPikBasis;\n        uint64 periodStart;\n        uint64 nextCapitalization;\n        // A replacement approval can authorize identical balances after a revoked or mistimed fact.\n        // The session roster still admits the facility once, regardless of this signed reference.\n        bytes32 approvalRef;\n    }\n\n    /// @notice Constant-time preparation status; nextFacilityId is zero when all rows are imported.\n    struct Progress {\n        uint256 nonce;\n        bytes32 sessionKey;\n        uint64 cutoff;\n        uint32 expected;\n        uint32 imported;\n        uint256 originalFace;\n        uint256 importedOriginalFace;\n        uint256 nextFacilityId;\n        bool active;\n    }\n\n    /// @notice Begins or advances a governed migration, or cancels it before its first import.\n    /// @dev step = abi.encode(uint8 action, bytes body). Actions: 0 begins with\n    ///      abi.encode(uint256[] sortedFacilityIds); 1 imports abi.encode(Opening[]);\n    ///      2 cancels with an empty body. Imports contain at most eight rows.\n    function prepareContinuousAccrualMigration(bytes calldata step) external;\n\n    /// @notice Returns preparation progress without quoting or advancing a partially imported book.\n    function accrualMigration() external view returns (Progress memory);\n}\n\n/// @notice Reserve-only continuation that installs opening risk after native face has been posted.\ninterface IAccrualMigrationRisk {\n    /// @return marked True even for a marked facility whose previous recorded contribution was zero.\n    function onAccrualOpening(uint256 facilityId, uint256 income) external returns (bool marked);\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/token/ERC721/utils/ERC721Utils.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/utils/ERC721Utils.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721Receiver} from \"../IERC721Receiver.sol\";\nimport {IERC721Errors} from \"../../../interfaces/draft-IERC6093.sol\";\n\n/**\n * @dev Library that provide common ERC-721 utility functions.\n *\n * See https://eips.ethereum.org/EIPS/eip-721[ERC-721].\n *\n * _Available since v5.1._\n */\nlibrary ERC721Utils {\n    /**\n     * @dev Performs an acceptance check for the provided `operator` by calling {IERC721Receiver-onERC721Received}\n     * on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).\n     *\n     * The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).\n     * Otherwise, the recipient must implement {IERC721Receiver-onERC721Received} and return the acceptance magic value to accept\n     * the transfer.\n     */\n    function checkOnERC721Received(\n        address operator,\n        address from,\n        address to,\n        uint256 tokenId,\n        bytes memory data\n    ) internal {\n        if (to.code.length > 0) {\n            try IERC721Receiver(to).onERC721Received(operator, from, tokenId, data) returns (bytes4 retval) {\n                if (retval != IERC721Receiver.onERC721Received.selector) {\n                    // Token rejected\n                    revert IERC721Errors.ERC721InvalidReceiver(to);\n                }\n            } catch (bytes memory reason) {\n                if (reason.length == 0) {\n                    // non-IERC721Receiver implementer\n                    revert IERC721Errors.ERC721InvalidReceiver(to);\n                } else {\n                    assembly (\"memory-safe\") {\n                        revert(add(reason, 0x20), mload(reason))\n                    }\n                }\n            }\n        }\n    }\n}\n"},{"file_path":"src/interfaces/IContinuousAccrual.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\n/// @title IContinuousAccrual\n/// @notice Reserve-owned accounting and exact delivery of previously accrued interest.\n/// @dev Separate from the legacy reserve interface so activation is explicit. Amounts are\n///      normalized to 18 decimals. Delivery changes physical balances, never economic ownership.\ninterface IContinuousAccrual {\n    /// @notice Modules bound to one independently backed chain instance.\n    /// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.\n    struct Modules {\n        address token;\n        address controller;\n        address vault;\n        address waterfall;\n        address bridge;\n        address registry;\n        address defaultManager;\n    }\n\n    /// @notice Constant-time accounting, capped at the first unprocessed schedule boundary.\n    /// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.\n    struct Snapshot {\n        uint256 gross;\n        uint256 unposted;\n        uint256 unissued;\n        uint256 seniorUnissued;\n        uint256 feeUnissued;\n        address feeRecipient;\n        uint64 accruedThrough;\n        bool enabled;\n        bool fresh;\n    }\n\n    /// @notice Vault-computed prices and permission for a neutral physical delivery.\n    /// @dev entryAssets includes any unvested assets; assets is the ordinary share-price base.\n    /// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.\n    struct PricingState {\n        uint256 assets;\n        uint256 entryAssets;\n        uint256 redemptionAssets;\n        uint256 performanceAssets;\n        uint256 feeAdjustedShares;\n        bool materializationAllowed;\n    }\n\n    /// @notice One immutable, same-transaction permit and coherent public price snapshot.\n    /// @dev Unselected amounts are zero. A zero/default inactive record grants no authority.\n    /// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.\n    struct Delivery {\n        uint256 nonce;\n        uint256 senior;\n        uint256 fee;\n        uint256 effectiveSupply;\n        uint256 backing;\n        uint256 recognizedBacking;\n        PricingState pricing;\n        address controller;\n        address vault;\n        address feeRecipient;\n        uint64 accruedThrough;\n        uint8 legs;\n        bool active;\n    }\n\n    /// @notice Reads the configured module identities, including before activation.\n    function accrualModules() external view returns (Modules memory);\n\n    /// @notice Reads recognized income and its outstanding physical posting/issuance.\n    function accrualSnapshot() external view returns (Snapshot memory);\n\n    /// @notice Reads the current delivery permit, or an inactive default record.\n    function accrualDelivery() external view returns (Delivery memory);\n\n    /// @notice Refuses a price-sensitive write at an unresolved accrual boundary or operation.\n    function requireAccrualFresh() external view;\n\n    /// @notice Delivers selected existing claims: senior=1, fee=2, both=3.\n    /// @dev No amount, destination, timestamp or fee rate is supplied by the caller.\n    function materializeAccrued(uint8 legs) external returns (uint256 senior, uint256 fee);\n}\n\n/// @notice Token continuation accepting only the bound reserve's current exact permit.\ninterface IAccrualToken {\n    /// @notice The immutable-once-configured accounting reserve, or zero before binding.\n    function accrualReserve() external view returns (address);\n\n    /// @notice Mints the selected legs of one unused, active delivery permit.\n    function mintAccrued(uint256 nonce) external;\n}\n\n/// @notice Controller continuation, callable only by its configured reserve.\ninterface IAccrualController {\n    /// @notice Relays one exact reserve-owned delivery permit to the token.\n    function mintAccrued(uint256 nonce) external;\n}\n\n/// @notice Vault views needed to admit a neutral delivery without a guarded write callback.\ninterface IAccrualVault {\n    /// @notice The immutable-once-configured accounting reserve, or zero before binding.\n    function accrualReserve() external view returns (address);\n\n    /// @notice Supplies a coherent price snapshot and current delivery admission state.\n    function accrualPricingState() external view returns (IContinuousAccrual.PricingState memory);\n}\n"},{"file_path":"src/libraries/AccrualCeiling.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport {AccrualMath} from \"./AccrualMath.sol\";\n\n/// @title AccrualCeiling\n/// @notice Conservative capacity for the full remaining signed PIK obligation.\n/// @dev This bound reserves arithmetic space; it never determines the interest actually earned.\n///      The first coupon uses the frozen basis. Successors compound only on signed boundaries.\n///      Rounding upward covers cumulative rounding carried through a migration cutoff and every\n///      downward-rounded contractual coupon. Exponentiation by squaring takes at most 64 steps.\nlibrary AccrualCeiling {\n    uint256 internal constant MAX_FACE = type(uint256).max / 10_000;\n    uint256 internal constant PRECISION = 1e27;\n\n    /// @notice Current exact face and the authenticated remaining fixed-rate schedule.\n    struct Terms {\n        uint256 face;\n        uint256 frozenBasis;\n        uint256 scale;\n        uint256 yearSeconds;\n        uint16 rateBps;\n        uint64 at;\n        uint64 nextCapitalization;\n        uint64 paymentInterval;\n        uint64 maturity;\n    }\n\n    /// @notice The conservative reservation exceeds the existing accounting domain.\n    error AccrualCeiling_ExposureCapacity();\n    /// @notice A remaining schedule must start before maturity and its first future boundary.\n    error AccrualCeiling_InvalidSchedule();\n\n    /// @notice Bounds full future face without walking contractual payment dates.\n    /// @param p Exact current debt, frozen first basis and signed future terms.\n    /// @return ceiling Upper bound on every remaining face, including uncapitalized maturity interest.\n    function pik(Terms memory p) internal pure returns (uint256 ceiling) {\n        if (p.face > MAX_FACE) revert AccrualCeiling_ExposureCapacity();\n        AccrualMath.earnedInterest(p.frozenBasis, p.rateBps, 0, p.yearSeconds);\n        if (p.scale == 0) revert AccrualMath.AccrualMath_ZeroScale();\n        uint64 firstEnd = p.nextCapitalization == 0 ? p.maturity : p.nextCapitalization;\n        if (p.paymentInterval == 0 || firstEnd <= p.at || firstEnd > p.maturity) {\n            revert AccrualCeiling_InvalidSchedule();\n        }\n        if (p.rateBps == 0) return p.face;\n        uint256 denominator = 10_000 * p.yearSeconds;\n        if (p.scale > type(uint256).max / denominator) revert AccrualCeiling_ExposureCapacity();\n        // floor(x + y) - floor(x) <= ceil(y), on the native reserve grid. This covers a\n        // migration's retained fractional entitlement without knowing its historical cursor.\n        uint256 firstUnits = _mulUp(p.frozenBasis, uint256(p.rateBps) * (firstEnd - p.at), denominator * p.scale);\n        if (firstUnits > (MAX_FACE - p.face) / p.scale) revert AccrualCeiling_ExposureCapacity();\n        ceiling = p.face + firstUnits * p.scale;\n        uint64 remaining = p.maturity - firstEnd;\n        uint64 count = remaining / p.paymentInterval;\n        if (count != 0) {\n            uint256 factor = PRECISION\n                + Math.mulDiv(uint256(p.rateBps) * p.paymentInterval, PRECISION, denominator, Math.Rounding.Ceil);\n            while (count != 0) {\n                if (count & 1 != 0) ceiling = _mulUp(ceiling, factor, PRECISION);\n                count >>= 1;\n                if (count != 0) factor = _mulUp(factor, factor, PRECISION);\n            }\n        }\n        // The final stub earns simple interest on the last capitalized basis.\n        uint64 stub = remaining % p.paymentInterval;\n        uint256 tail = _mulUp(ceiling, uint256(p.rateBps) * stub, denominator);\n        if (tail > MAX_FACE - ceiling) revert AccrualCeiling_ExposureCapacity();\n        return ceiling + tail;\n    }\n\n    /// @dev Refuse an unrepresentable bound with a named error before full-precision division.\n    function _mulUp(uint256 x, uint256 y, uint256 denominator) private pure returns (uint256 result) {\n        (uint256 high,) = Math.mul512(x, y);\n        if (high >= denominator) revert AccrualCeiling_ExposureCapacity();\n        result = Math.mulDiv(x, y, denominator);\n        if (result > MAX_FACE) revert AccrualCeiling_ExposureCapacity();\n        if (mulmod(x, y, denominator) != 0) {\n            if (result == MAX_FACE) revert AccrualCeiling_ExposureCapacity();\n            ++result;\n        }\n    }\n}\n"},{"file_path":"src/libraries/BorrowerPayoutLib.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {IComplianceRegistry} from \"../interfaces/IComplianceRegistry.sol\";\n\n/// @title BorrowerPayoutLib\n/// @notice One permanent borrower-payout policy shared by each enforcing proxy.\n/// @dev Public functions are linked delegatecalls so ClaimBridge and ReserveManager retain\n///      EIP-170 margin. `requireAllowedInternal` is used only inside ReserveCreditLib; keeping\n///      that call internal avoids a library-to-library link placeholder.\nlibrary BorrowerPayoutLib {\n    /// @custom:storage-location erc7201:forestroad.storage.BorrowerPayout\n    struct PayoutStorage {\n        IComplianceRegistry registry;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"forestroad.storage.BorrowerPayout\")) - 1)) &\n    // ~bytes32(uint256(0xff))\n    bytes32 private constant PAYOUT_STORAGE_LOCATION =\n        0xcc930b8edba69cb0a1dc2a36aaecdb484adbaed2a72b4ed757bcdf5993738500;\n\n    error BorrowerPayout_RegistryAlreadySet(address registry);\n    error BorrowerPayout_InvalidRegistry(address registry);\n    error BorrowerPayout_RecipientNotAllowed(address recipient);\n\n    event BorrowerPayoutRegistrySet(address indexed registry);\n\n    /// @notice Permanently binds a compatible registry in the caller proxy's namespace.\n    /// @return bound The registry address, returned so the delegatecall needs no codeless guard.\n    function bind(address registry_) public returns (address bound) {\n        PayoutStorage storage $ = _storage();\n        address current = address($.registry);\n        if (current != address(0)) revert BorrowerPayout_RegistryAlreadySet(current);\n        if (!_isRegistry(registry_)) revert BorrowerPayout_InvalidRegistry(registry_);\n        $.registry = IComplianceRegistry(registry_);\n        emit BorrowerPayoutRegistrySet(registry_);\n        return registry_;\n    }\n\n    /// @notice Returns the registry stored in the caller proxy's namespace.\n    function registry() public view returns (address) {\n        return address(_storage().registry);\n    }\n\n    /// @notice Refuses an unbound, revoked or jurisdiction-blocked recipient.\n    /// @return allowed Always true on success, returned to keep the linked call compact.\n    function requireAllowed(address recipient) public view returns (bool allowed) {\n        _requireAllowed(recipient);\n        return true;\n    }\n\n    /// @dev Inlined into ReserveCreditLib; do not make that library call a second public library.\n    function requireAllowedInternal(address recipient) internal view {\n        _requireAllowed(recipient);\n    }\n\n    function _requireAllowed(address recipient) private view {\n        IComplianceRegistry policy = _storage().registry;\n        if (address(policy) == address(0) || !policy.isFundingRecipientAllowed(recipient)) {\n            revert BorrowerPayout_RecipientNotAllowed(recipient);\n        }\n    }\n\n    function _isRegistry(address registry_) private view returns (bool valid) {\n        if (registry_.code.length == 0) return false;\n        (bool ok, bytes memory data) =\n            registry_.staticcall(abi.encodeCall(IComplianceRegistry.isFundingRecipientAllowed, (address(0))));\n        if (!ok || data.length != 32) return false;\n        uint256 word;\n        assembly (\"memory-safe\") {\n            word := mload(add(data, 0x20))\n        }\n        return word <= 1;\n    }\n\n    function _storage() private pure returns (PayoutStorage storage $) {\n        assembly {\n            $.slot := PAYOUT_STORAGE_LOCATION\n        }\n    }\n}\n"},{"file_path":"src/libraries/AccrualBook.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport {AccrualSchedule} from \"./AccrualSchedule.sol\";\n\n/// @title AccrualBook\n/// @notice Additive continuous loan-interest accounting, posting, issuance and risk cohorts.\n/// @dev Embed Book in the reserve's ERC-7201 namespace. All methods are internal and perform no\n///      external calls. The host validates funded contractual terms and owns authority, timestamps,\n///      capacity admission, cash custody, registry posting and token issuance. Segment slopes are\n///      integer normalized wei per second, so facility and aggregate amounts add exactly. The\n///      remainder is recognized once at the scheduled endpoint, or cumulatively before an\n///      authenticated lifecycle change. At most one year per technical segment bounds the interim\n///      lag below 31,536,000 normalized wei per facility relative to its endpoint interpolation.\n///      Technical segment boundaries do not themselves change a loan's contractual PIK basis.\nlibrary AccrualBook {\n    using AccrualSchedule for AccrualSchedule.Heap;\n\n    uint64 internal constant MAX_SEGMENT_SECONDS = 365 days;\n    uint32 internal constant MAX_FACILITIES = 100;\n\n    /// @notice An exactly additive integer rate and its settled value.\n    /// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.\n    struct Clock {\n        uint256 value;\n        uint256 rate;\n        uint64 at;\n    }\n\n    /// @notice Recognition and posting totals for one exposure grouping.\n    struct Group {\n        Clock clock;\n        uint256 posted;\n    }\n\n    /// @notice A funded facility's cumulative recognition and current technical segment.\n    /// @dev keys are distinct domain-separated class, borrower and jurisdiction identifiers.\n    struct Entry {\n        Clock clock;\n        uint256 posted;\n        uint256 segmentAmount;\n        uint256 roundingCredited;\n        uint64 start;\n        uint64 end;\n        bytes32[3] keys;\n        bool known;\n        bool registered;\n        bool scheduled;\n        bool pastDue;\n    }\n\n    /// @notice The reserve-local authoritative book.\n    /// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.\n    struct Book {\n        Clock total;\n        mapping(uint256 facilityId => Entry) entries;\n        mapping(bytes32 key => Group) groups;\n        mapping(bytes32 classKey => Clock) pastDueUnposted;\n        AccrualSchedule.Heap schedule;\n        uint256 posted;\n        uint256 seniorIssued;\n        uint256 feeIssued;\n        uint256 feeBaseGross;\n        uint256 feeBaseAmount;\n        uint32 registered;\n        uint16 feeBps;\n        bool initialized;\n        uint256 unearned;\n    }\n\n    /// @notice A coherent view capped at the first unprocessed boundary.\n    struct Snapshot {\n        uint256 gross;\n        uint256 fee;\n        uint256 unposted;\n        uint256 unissued;\n        uint256 seniorUnissued;\n        uint256 feeUnissued;\n        uint64 accruedThrough;\n        bool fresh;\n    }\n\n    /// @notice An uninitialized book cannot accept accounting changes.\n    error AccrualBook_NotInitialized();\n    /// @notice Reinitialization would discard existing obligations.\n    error AccrualBook_AlreadyInitialized();\n    /// @notice An interest fee cannot exceed the gross interest earned.\n    error AccrualBook_InvalidFee(uint16 feeBps);\n    /// @notice Issuance selects senior (1), protocol fee (2), or both (3), and no other mask.\n    error AccrualBook_InvalidIssuanceLegs(uint8 legs);\n    /// @notice The initial 100-facility admission envelope is full.\n    error AccrualBook_Capacity();\n    /// @notice Facility identifiers cannot be reused, including after retirement.\n    error AccrualBook_KnownFacility(uint256 facilityId);\n    /// @notice The facility is not registered in this book.\n    error AccrualBook_UnknownFacility(uint256 facilityId);\n    /// @notice A facility can have only one active technical segment.\n    error AccrualBook_AlreadyScheduled(uint256 facilityId);\n    /// @notice Technical segments must be positive and no longer than one year.\n    error AccrualBook_InvalidSegment(uint64 start, uint64 end);\n    /// @notice Exposure grouping identifiers must be nonzero and pairwise distinct.\n    error AccrualBook_InvalidKeys();\n    /// @notice An accounting clock cannot be read or changed backwards.\n    error AccrualBook_TimeReversed(uint64 previous, uint64 requested);\n    /// @notice Chronological maintenance must process the earliest boundary first.\n    error AccrualBook_BoundaryPending(uint64 boundary, uint64 requested);\n    /// @notice No scheduled boundary is due at the supplied time.\n    error AccrualBook_NoBoundaryDue();\n    /// @notice Retirement requires no scheduled segment and no unposted interest.\n    error AccrualBook_UnsettledFacility(uint256 facilityId);\n    /// @notice An arithmetic result would exceed uint256.\n    error AccrualBook_Overflow();\n\n    /// @notice Records the start of the book and the configured gross-interest fee.\n    function initialize(Book storage self, uint64 at, uint16 feeBps) internal {\n        if (self.initialized) revert AccrualBook_AlreadyInitialized();\n        _validateFee(feeBps);\n        self.total.at = at;\n        self.feeBps = feeBps;\n        self.initialized = true;\n    }\n\n    /// @notice Registers a proved funded facility and its immutable exposure identities.\n    /// @dev Does not itself create interest, change principal or install a contractual schedule.\n    function register(Book storage self, uint256 facilityId, bytes32[3] memory keys, uint64 at) internal {\n        _requireInitialized(self);\n        requireFresh(self, at);\n        Entry storage e = self.entries[facilityId];\n        if (e.known) revert AccrualBook_KnownFacility(facilityId);\n        if (self.registered == MAX_FACILITIES) revert AccrualBook_Capacity();\n        if (\n            keys[0] == 0 || keys[1] == 0 || keys[2] == 0 || keys[0] == keys[1] || keys[0] == keys[2]\n                || keys[1] == keys[2]\n        ) revert AccrualBook_InvalidKeys();\n        _settleTotal(self, at);\n        e.clock.at = at;\n        e.keys = keys;\n        e.known = true;\n        e.registered = true;\n        ++self.registered;\n    }\n\n    /// @notice Starts a proved fixed-endpoint segment at the accounting frontier.\n    /// @dev A host may continue a completed segment at its historical boundary during catch-up.\n    ///      It must install the successor atomically with finishNext; no external callback may see\n    ///      a missing successor. The endpoint excludes amounts recognized by earlier segments.\n    function open(Book storage self, uint256 facilityId, uint256 amount, uint64 start, uint64 end) internal {\n        Entry storage e = _entry(self, facilityId);\n        _requireTime(self, start);\n        if (e.scheduled) revert AccrualBook_AlreadyScheduled(facilityId);\n        if (end <= start || end - start > MAX_SEGMENT_SECONDS) {\n            revert AccrualBook_InvalidSegment(start, end);\n        }\n        _settleTotal(self, start);\n        // Reserve the entire endpoint before admitting a slope. Otherwise several individually\n        // valid endpoints could make every future NAV read overflow, after admission succeeded.\n        if (amount > type(uint256).max - self.total.value - self.unearned) revert AccrualBook_Overflow();\n        self.unearned += amount;\n        uint256 rate = amount / (end - start);\n        _changeRate(self, e, rate, true, start);\n        e.start = start;\n        e.end = end;\n        e.segmentAmount = amount;\n        e.roundingCredited = 0;\n        e.scheduled = true;\n        self.schedule.insert(facilityId, end);\n    }\n\n    /// @notice Reads effective recognition and remaining obligations without a facility scan.\n    /// @dev A never-enabled book returns zero and fresh, for an explicit legacy/off state.\n    function snapshot(Book storage self, uint64 at) internal view returns (Snapshot memory s) {\n        s.accruedThrough = at;\n        s.fresh = true;\n        if (!self.initialized) return s;\n        if (self.schedule.count() != 0) {\n            uint64 boundary = self.schedule.peek().deadline;\n            if (boundary <= at) {\n                s.accruedThrough = boundary;\n                s.fresh = false;\n            }\n        }\n        s.gross = _preview(self.total, s.accruedThrough);\n        s.fee = _add(self.feeBaseAmount, Math.mulDiv(s.gross - self.feeBaseGross, self.feeBps, 10_000));\n        s.unposted = s.gross - self.posted;\n        s.feeUnissued = s.fee - self.feeIssued;\n        s.seniorUnissued = s.gross - s.fee - self.seniorIssued;\n        s.unissued = _add(s.feeUnissued, s.seniorUnissued);\n    }\n\n    /// @notice Rejects a price-sensitive mutation when a boundary is due but unprocessed.\n    function requireFresh(Book storage self, uint64 at) internal view {\n        _requireTime(self, at);\n        if (self.schedule.count() != 0 && self.schedule.peek().deadline == at) {\n            revert AccrualBook_BoundaryPending(at, at);\n        }\n    }\n\n    /// @notice Cumulative recognized interest for a single registered facility.\n    function earned(Book storage self, uint256 facilityId, uint64 at) internal view returns (uint256) {\n        Entry storage e = _entry(self, facilityId);\n        return _preview(e.clock, _frontier(self, at));\n    }\n\n    /// @notice Unposted gross interest for one class, borrower or jurisdiction, in O(1).\n    function groupUnposted(Book storage self, bytes32 key, uint64 at) internal view returns (uint256) {\n        Group storage g = self.groups[key];\n        return _preview(g.clock, _frontier(self, at)) - g.posted;\n    }\n\n    /// @notice Additional unposted interest on the live past-due cohort of one class.\n    /// @dev The default manager adds its existing recorded-face risk to this amount. Posting\n    ///      transfers the identical amount to that recorded face; clearing a cohort removes it.\n    function pastDueInterest(Book storage self, bytes32 classKey, uint64 at) internal view returns (uint256) {\n        return _preview(self.pastDueUnposted[classKey], _frontier(self, at));\n    }\n\n    /// @notice Settles already streamed growth without recognizing a new rounding remainder.\n    function checkpoint(Book storage self, uint64 at) internal {\n        _requireInitialized(self);\n        _requireTime(self, at);\n        _settleTotal(self, at);\n    }\n\n    /// @notice Recognizes the exact cumulative segment interpolation before a lifecycle action.\n    /// @dev Idempotent at the same time and independent of earlier reconciliations. The host may\n    ///      call this before an authenticated repayment/amendment/default. Ordinary keeper\n    ///      checkpoints use checkpoint instead. This operation cannot change the segment's basis.\n    function reconcile(Book storage self, uint256 facilityId, uint64 at) internal returns (uint256 extra) {\n        Entry storage e = _entry(self, facilityId);\n        _requireTime(self, at);\n        if (!e.scheduled) return 0;\n        uint64 elapsed = at - e.start;\n        uint64 duration = e.end - e.start;\n        uint256 remainder = e.segmentAmount % duration;\n        uint256 cumulative = Math.mulDiv(remainder, elapsed, duration);\n        extra = cumulative - e.roundingCredited;\n        e.roundingCredited = cumulative;\n        _credit(self, e, extra, at);\n    }\n\n    /// @notice Finishes the earliest due technical segment and recognizes its endpoint exactly.\n    /// @return facilityId The facility whose successor the host must install or explicitly stop.\n    /// @return boundary The deterministic endpoint timestamp, which may precede the current clock.\n    /// @return extra The previously unrecognized rounding remainder credited at this boundary.\n    function finishNext(Book storage self, uint64 at)\n        internal\n        returns (uint256 facilityId, uint64 boundary, uint256 extra)\n    {\n        _requireInitialized(self);\n        if (self.schedule.count() == 0) revert AccrualBook_NoBoundaryDue();\n        AccrualSchedule.Event memory next = self.schedule.peek();\n        if (next.deadline > at) revert AccrualBook_NoBoundaryDue();\n        facilityId = next.facilityId;\n        boundary = next.deadline;\n        extra = reconcile(self, facilityId, boundary);\n        Entry storage e = self.entries[facilityId];\n        _changeRate(self, e, e.clock.rate, false, boundary);\n        self.schedule.pop();\n        e.scheduled = false;\n    }\n\n    /// @notice Stops future recognition at an authenticated lifecycle timestamp.\n    /// @dev Credits exact partial interpolation before removing the integer slope. Recognized\n    ///      income is retained for posting and the native loss cascade; it is never cancelled.\n    function stop(Book storage self, uint256 facilityId, uint64 at) internal returns (uint256 extra) {\n        Entry storage e = _entry(self, facilityId);\n        _requireTime(self, at);\n        if (!e.scheduled) return 0;\n        extra = reconcile(self, facilityId, at);\n        uint256 remaining = e.segmentAmount - e.clock.rate * (at - e.start) - e.roundingCredited;\n        _changeRate(self, e, e.clock.rate, false, at);\n        self.unearned -= remaining;\n        self.schedule.remove(facilityId);\n        e.scheduled = false;\n    }\n\n    /// @notice Credits a proved positive contractual correction after a segment has stopped.\n    /// @dev The host must derive the canonical discrepancy, prove its applicable bound (including\n    ///      the possible one-scale-unit positive difference), and prevent replay. This internal\n    ///      accounting primitive grants no external authority and does not validate signed terms.\n    ///      The entry must be registered and unscheduled. Reserve the correction against complete\n    ///      portfolio commitments before consuming it through the ordinary global, facility,\n    ///      exposure-group and past-due credit path. No historical counter is reduced or reset.\n    ///      Zero is permitted and advances the shared accounting clock without recognizing income.\n    /// @param self The reserve-local book.\n    /// @param facilityId The registered facility with no active segment.\n    /// @param amount The independently proved additional gross entitlement.\n    /// @param at The chronological correction timestamp; an in-progress boundary may equal it.\n    function creditStoppedCorrection(Book storage self, uint256 facilityId, uint256 amount, uint64 at) internal {\n        Entry storage e = _entry(self, facilityId);\n        _requireTime(self, at);\n        if (e.scheduled) revert AccrualBook_AlreadyScheduled(facilityId);\n        _settleTotal(self, at);\n        if (amount > type(uint256).max - self.total.value - self.unearned) revert AccrualBook_Overflow();\n        self.unearned += amount;\n        _credit(self, e, amount, at);\n    }\n\n    /// @notice Transfers a facility's recognized income to its recorded reserve/registry face.\n    /// @dev The host must raise both recorded faces by returned amount in the same protected\n    ///      operation. No token is minted here. This call does not reconcile new rounding income.\n    function takePosting(Book storage self, uint256 facilityId, uint64 at) internal returns (uint256 amount) {\n        Entry storage e = _entry(self, facilityId);\n        _requireTime(self, at);\n        _settleTotal(self, at);\n        _checkpoint(e.clock, at);\n        amount = e.clock.value - e.posted;\n        e.posted = e.clock.value;\n        self.posted = _add(self.posted, amount);\n        for (uint256 i; i < 3; ++i) {\n            Group storage g = self.groups[e.keys[i]];\n            g.posted = _add(g.posted, amount);\n        }\n        if (e.pastDue) {\n            Clock storage risk = self.pastDueUnposted[e.keys[0]];\n            _checkpoint(risk, at);\n            risk.value -= amount;\n        }\n    }\n\n    /// @notice Transfers outstanding senior/fee obligations to physical token issuance.\n    /// @dev The host must mint both returned amounts under its coherent snapshot/operation lock,\n    ///      prove raw token deltas, and revert the entire operation on failure. Permission to call\n    ///      this library is not permission to mint elsewhere. No rounding income is added here.\n    function takeIssuance(Book storage self, uint64 at) internal returns (uint256 senior, uint256 fee) {\n        return takeIssuance(self, 3, at);\n    }\n\n    /// @notice Transfers selected senior and/or protocol-fee obligations to physical issuance.\n    /// @dev Unselected obligations remain virtual and their issued counters do not change. The\n    ///      host must mint exactly the returned amounts under its coherent operation lock and\n    ///      prove raw token deltas. Selection neither forfeits nor redirects the other claim.\n    ///      This method advances the shared accounting clock even if selected amounts are zero.\n    /// @param self The reserve-local book.\n    /// @param legs Senior only (1), protocol fee only (2), or both (3).\n    /// @param at The current chronological timestamp, with all due boundaries processed.\n    /// @return senior The selected senior entitlement to issue, otherwise zero.\n    /// @return fee The selected protocol-fee entitlement to issue, otherwise zero.\n    function takeIssuance(Book storage self, uint8 legs, uint64 at) internal returns (uint256 senior, uint256 fee) {\n        _requireInitialized(self);\n        if (legs == 0 || legs > 3) revert AccrualBook_InvalidIssuanceLegs(legs);\n        requireFresh(self, at);\n        Snapshot memory s = snapshot(self, at);\n        _settleTotal(self, at);\n        if ((legs & 1) != 0) {\n            senior = s.seniorUnissued;\n            self.seniorIssued = _add(self.seniorIssued, senior);\n        }\n        if ((legs & 2) != 0) {\n            fee = s.feeUnissued;\n            self.feeIssued = _add(self.feeIssued, fee);\n        }\n    }\n\n    /// @notice Changes the configured fee prospectively after settling the previous fee epoch.\n    /// @dev Keeping the same rate is a no-op and cannot reset fractional fee rounding. The existing\n    ///      vault performance fee is separate and consumes the resulting senior entitlement.\n    function setFee(Book storage self, uint16 feeBps, uint64 at) internal {\n        _requireInitialized(self);\n        _validateFee(feeBps);\n        requireFresh(self, at);\n        if (self.feeBps == feeBps) return;\n        Snapshot memory s = snapshot(self, at);\n        _settleTotal(self, at);\n        self.feeBaseGross = s.gross;\n        self.feeBaseAmount = s.fee;\n        self.feeBps = feeBps;\n    }\n\n    /// @notice Adds or removes a facility from the class's continuously growing past-due cohort.\n    /// @dev Existing unposted interest joins/leaves along with the slope. The default-manager\n    ///      host must keep recorded-face contributions synchronized with takePosting separately.\n    function setPastDue(Book storage self, uint256 facilityId, bool enabled, uint64 at) internal {\n        Entry storage e = _entry(self, facilityId);\n        _requireTime(self, at);\n        if (e.pastDue == enabled) return;\n        _settleTotal(self, at);\n        _checkpoint(e.clock, at);\n        Clock storage risk = self.pastDueUnposted[e.keys[0]];\n        _checkpoint(risk, at);\n        uint256 unposted = e.clock.value - e.posted;\n        if (enabled) {\n            risk.value = _add(risk.value, unposted);\n            risk.rate = _add(risk.rate, e.clock.rate);\n        } else {\n            risk.value -= unposted;\n            risk.rate -= e.clock.rate;\n        }\n        e.pastDue = enabled;\n    }\n\n    /// @notice Frees an admission slot after the host proves the facility has been fully resolved.\n    /// @dev Historical recognition, posting, exposure groups and the known-ID tombstone survive.\n    function retire(Book storage self, uint256 facilityId, uint64 at) internal {\n        Entry storage e = _entry(self, facilityId);\n        _requireTime(self, at);\n        if (e.scheduled || e.clock.value != e.posted) revert AccrualBook_UnsettledFacility(facilityId);\n        _settleTotal(self, at);\n        setPastDue(self, facilityId, false, at);\n        e.registered = false;\n        --self.registered;\n    }\n\n    function _changeRate(Book storage self, Entry storage e, uint256 rate, bool add, uint64 at) private {\n        _settleTotal(self, at);\n        self.total.rate = add ? _add(self.total.rate, rate) : self.total.rate - rate;\n        _rate(e.clock, rate, add, at);\n        for (uint256 i; i < 3; ++i) {\n            _rate(self.groups[e.keys[i]].clock, rate, add, at);\n        }\n        if (e.pastDue) _rate(self.pastDueUnposted[e.keys[0]], rate, add, at);\n    }\n\n    function _credit(Book storage self, Entry storage e, uint256 amount, uint64 at) private {\n        _settleTotal(self, at);\n        _checkpoint(e.clock, at);\n        self.unearned -= amount;\n        self.total.value = _add(self.total.value, amount);\n        e.clock.value = _add(e.clock.value, amount);\n        for (uint256 i; i < 3; ++i) {\n            Clock storage c = self.groups[e.keys[i]].clock;\n            _checkpoint(c, at);\n            c.value = _add(c.value, amount);\n        }\n        if (e.pastDue) {\n            Clock storage risk = self.pastDueUnposted[e.keys[0]];\n            _checkpoint(risk, at);\n            risk.value = _add(risk.value, amount);\n        }\n    }\n\n    function _rate(Clock storage c, uint256 amount, bool add, uint64 at) private {\n        _checkpoint(c, at);\n        c.rate = add ? _add(c.rate, amount) : c.rate - amount;\n    }\n\n    function _checkpoint(Clock storage c, uint64 at) private {\n        c.value = _preview(c, at);\n        c.at = at;\n    }\n\n    function _settleTotal(Book storage self, uint64 at) private {\n        uint256 previous = self.total.value;\n        _checkpoint(self.total, at);\n        self.unearned -= self.total.value - previous;\n    }\n\n    function _preview(Clock storage c, uint64 at) private view returns (uint256 value) {\n        if (at < c.at) revert AccrualBook_TimeReversed(c.at, at);\n        uint256 elapsed = at - c.at;\n        uint256 growth;\n        unchecked {\n            growth = c.rate * elapsed;\n        }\n        if (elapsed != 0 && growth / elapsed != c.rate) revert AccrualBook_Overflow();\n        value = _add(c.value, growth);\n    }\n\n    function _frontier(Book storage self, uint64 at) private view returns (uint64) {\n        if (self.schedule.count() != 0) {\n            uint64 boundary = self.schedule.peek().deadline;\n            if (boundary < at) return boundary;\n        }\n        return at;\n    }\n\n    function _requireTime(Book storage self, uint64 at) private view {\n        if (at < self.total.at) revert AccrualBook_TimeReversed(self.total.at, at);\n        if (self.schedule.count() != 0) {\n            uint64 boundary = self.schedule.peek().deadline;\n            if (boundary < at) revert AccrualBook_BoundaryPending(boundary, at);\n        }\n    }\n\n    function _entry(Book storage self, uint256 facilityId) private view returns (Entry storage e) {\n        _requireInitialized(self);\n        e = self.entries[facilityId];\n        if (!e.registered) revert AccrualBook_UnknownFacility(facilityId);\n    }\n\n    function _requireInitialized(Book storage self) private view {\n        if (!self.initialized) revert AccrualBook_NotInitialized();\n    }\n\n    function _validateFee(uint16 feeBps) private pure {\n        if (feeBps > 10_000) revert AccrualBook_InvalidFee(feeBps);\n    }\n\n    function _add(uint256 a, uint256 b) private pure returns (uint256 result) {\n        unchecked {\n            result = a + b;\n        }\n        if (result < a) revert AccrualBook_Overflow();\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"../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"},{"file_path":"lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol","source_code":"// 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"},{"file_path":"src/libraries/AccrualLoans.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport {AccrualBook} from \"./AccrualBook.sol\";\nimport {AccrualMath} from \"./AccrualMath.sol\";\nimport {AccrualSchedule} from \"./AccrualSchedule.sol\";\nimport {AccrualSegments} from \"./AccrualSegments.sol\";\n\n/// @title AccrualLoans\n/// @notice Reserve-local coordination of proved fixed cash and PIK loan terms.\n/// @dev All functions are internal. The host authenticates funding, amendments, payments and\n///      declaration times; locks callback-visible accounting; executes returned native posting,\n///      receipt, rounding-loss and bridge work atomically; and emits the corresponding events.\n///      This library makes no external calls or token/custody/registry writes. A caller must never\n///      expose an external arbitrary timestamp, term, correction or loss setter around these APIs.\nlibrary AccrualLoans {\n    using AccrualBook for AccrualBook.Book;\n    using AccrualSchedule for AccrualSchedule.Heap;\n\n    /// @notice Work reservations use an elapsed 365-day engineering year.\n    uint256 internal constant YEAR = 365 days;\n    /// @notice Conservative aggregate autonomous boundary envelope; no individual interval floor.\n    /// @dev The contract can close 32 boundaries per transaction. Cold mixed-state measurement\n    ///      fixes the funded keeper at 24 and 128 maintenance transactions per day. At this cap,\n    ///      normal maximum work needs 12 checkpoint transactions per day; seven completely missed\n    ///      days create fewer than 1,920 boundaries and use at most 80 catch-up transactions.\n    ///      The former `YEAR + 400` value admitted one boundary every second (86,400 per day),\n    ///      which no configured keeper could ever service and could hold every price-writing path\n    ///      behind the global freshness gate indefinitely. This remains an aggregate capacity\n    ///      limit: each note still selects its own contractual compounding interval.\n    uint256 internal constant MAX_ANNUAL_WORK = 100_000;\n    /// @notice Maximum chronological work returned by one keeper call.\n    uint256 internal constant MAX_BATCH = 32;\n    /// @notice The admitted AccrualMath basis domain also bounds every future contractual basis.\n    uint256 internal constant MAX_BASIS = type(uint256).max / 10_000;\n\n    /// @notice Embedded in the reserve's own ERC-7201 namespace.\n    /// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.\n    struct State {\n        AccrualBook.Book book;\n        mapping(uint256 facilityId => Loan) loans;\n        uint256 annualWork;\n    }\n\n    /// @notice Contractual debt and the current arithmetic epoch, distinct from booked history.\n    /// @dev unpaidInterest is canonical through the last closed technical segment. Current\n    ///      unclosed interest is supplied by loanFace. Cash never adds unpaidInterest to basis.\n    ///      Cap-paused loans retain active and their work reservation. nextCapitalization is zero\n    ///      when no further signed PIK boundary fits before maturity; for cash it stores the signed\n    ///      payment due date and is changed only by an authenticated amendment.\n    struct Loan {\n        AccrualSegments.Terms terms;\n        uint256 principal;\n        uint256 unpaidInterest;\n        uint256 balanceCeiling;\n        uint256 frozenPikBasis;\n        uint256 segmentBookBase;\n        uint256 segmentCumulativeStart;\n        uint256 workWeight;\n        uint64 nextCapitalization;\n        uint64 paymentInterval;\n        uint64 legalMaturity;\n        uint64 lastSettlement;\n        uint64 closureNonce;\n        bool pik;\n        bool active;\n        bool configured;\n        bool permanentlyStopped;\n        // Mixed cash/PIK fields are tail-appended to this mapping value. Legacy entries read zero.\n        uint256 unpaidCashInterest;\n        uint256 mixedCashBasis;\n        uint256 mixedCashCarry;\n        uint256 mixedPikCarry;\n        uint256 mixedCashRemainder;\n        uint256 mixedPikRemainder;\n        uint256 mixedCashSegmentCumulativeStart;\n        uint64 mixedRateStart;\n        uint16 mixedCashRateBps;\n        bool mixed;\n    }\n\n    /// @notice Validated funded terms; rate/day-count support is explicit in this representation.\n    /// @dev frozenPikBasis == 0 uses principal for ordinary funding. A nonzero PIK value is only\n    ///      for an authenticated prospective migration of an existing frozen contractual cursor;\n    ///      it does not import or recreate any historical interest in Book. Cash requires zero.\n    struct Funding {\n        uint256 principal;\n        uint256 balanceCeiling;\n        uint256 scale;\n        uint256 yearSeconds;\n        uint16 rateBps;\n        uint64 fundedAt;\n        uint64 nextPaymentDue;\n        uint64 paymentInterval;\n        uint64 maturity;\n        bool pik;\n        bytes32[3] keys;\n        uint256 frozenPikBasis;\n    }\n\n    /// @notice New-facility terms for concurrent cash and PIK accrual.\n    /// @dev `pikTerms.rateBps` is the PIK rate and its dates are capitalization dates. Cash and\n    ///      PIK share Actual/360, maturity, scale and the admitted aggregate balance ceiling.\n    struct MixedFunding {\n        Funding pikTerms;\n        uint16 cashRateBps;\n    }\n\n    /// @notice Authenticated opening debt at terms.fundedAt, used as the migration cutoff.\n    /// @dev recordedFace is the reserve face already backing issued tokens. Only the excess\n    ///      of principal plus interest over that face enters Book as newly recognized income.\n    ///      periodStart preserves the original contractual rounding cursor. The host must prove\n    ///      every field, the legacy asset/identity mapping, the complete portfolio and stop status.\n    ///      This internal routine authorizes no migration and performs no native ledger writes.\n    struct Opening {\n        Funding terms;\n        uint256 recordedFace;\n        uint256 interest;\n        uint64 periodStart;\n        bool permanentlyStopped;\n    }\n\n    /// @notice Forward terms proved by the bridge's existing signed amendment process.\n    /// @dev nextPaymentDue replaces the future signed PIK boundary without capitalizing now.\n    struct Amendment {\n        uint256 balanceCeiling;\n        uint256 yearSeconds;\n        uint16 rateBps;\n        uint64 nextPaymentDue;\n        uint64 paymentInterval;\n        uint64 maturity;\n    }\n\n    /// @notice Prospective concurrent-leg terms proved by the bridge's mixed amendment path.\n    struct MixedAmendment {\n        Amendment pikTerms;\n        uint16 cashRateBps;\n    }\n\n    /// @notice Work that the host must execute once, within its protected accounting operation.\n    /// @dev posting raises recorded reserve/registry face; roundingLoss then reduces that face\n    ///      through the native loss policy. Receipt reductions are separate from those effects.\n    ///      A checkpoint's posting is zero: its income remains virtually backed until post or a\n    ///      lifecycle operation. capitalized is only a PIK debt reclassification, never new yield.\n    struct LifecycleWork {\n        uint256 facilityId;\n        uint64 closureNonce;\n        uint64 at;\n        uint256 positiveCorrection;\n        uint256 roundingLoss;\n        uint256 posting;\n        uint256 principalReduction;\n        uint256 interestReduction;\n        uint256 capitalized;\n        uint64 previousDue;\n        uint64 nextDue;\n        bool stopped;\n        bool repaid;\n    }\n\n    /// @dev One aggregate segment backed by two fixed-rate curves.\n    struct MixedSegment {\n        uint256 cumulativeStart;\n        uint256 cashCumulativeStart;\n        uint256 amount;\n        uint64 end;\n    }\n\n    /// @notice No contractual metadata was configured for this identifier.\n    error AccrualLoans_Unknown(uint256 facilityId);\n    /// @notice Default/declaration or complete repayment cannot be reversed by an amendment.\n    error AccrualLoans_Inactive(uint256 facilityId);\n    /// @notice Funded principal, ceiling or optional PIK migration basis is invalid.\n    error AccrualLoans_InvalidFunding();\n    /// @notice Opening debt cannot reduce recognized backing or discard its contractual cursor.\n    error AccrualLoans_InvalidOpening();\n    /// @notice Signed due, interval and maturity must define a valid forward schedule.\n    error AccrualLoans_InvalidSchedule();\n    /// @notice A future balance ceiling exceeds the admitted math domain.\n    error AccrualLoans_InvalidCeiling(uint256 ceiling);\n    /// @notice The resulting aggregate annual work reservation exceeds the engineering ceiling.\n    error AccrualLoans_WorkCapacity(uint256 requested);\n    /// @notice A maintenance request must process between one and 32 boundaries.\n    error AccrualLoans_BadBatch(uint256 maximum);\n    /// @notice A payment must be positive and its combined legs must lie on the reserve grid.\n    error AccrualLoans_BadPayment();\n    /// @notice Existing PIK payment semantics require a zero separately designated interest leg.\n    error AccrualLoans_PikInterestLeg();\n    /// @notice A payment cannot discharge more than its contractual claim.\n    error AccrualLoans_PaymentAboveDebt();\n    /// @notice A closure failed the mathematically proved canonical/interpolation discrepancy bound.\n    error AccrualLoans_CorrectionOutsideBound(uint256 discrepancy, uint256 scale);\n    /// @notice Retirement requires the entire contractual debt to be discharged and stopped.\n    error AccrualLoans_Unsettled(uint256 facilityId);\n    /// @notice An amount or closure sequence would exceed its stored integer domain.\n    error AccrualLoans_Overflow();\n    /// @notice Mixed entry points require two positive fixed rates whose sum fits the protocol cap.\n    error AccrualLoans_InvalidMixedTerms();\n    /// @notice A mixed facility cannot be changed through a legacy single-leg lifecycle entry point.\n    error AccrualLoans_MixedLifecycleRequired(uint256 facilityId);\n\n    /// @notice Initializes the reserve-local book at the host's accepted current timestamp.\n    function initialize(State storage self, uint64 at, uint16 feeBps) internal {\n        self.book.initialize(at, feeBps);\n    }\n\n    /// @notice Registers funded fixed-rate debt and opens its first eligible segment.\n    /// @dev principal includes the host's proved financed-fee treatment. Both principal and the\n    ///      entire future balance ceiling must fit AccrualMath's existing basis domain.\n    function fund(State storage self, uint256 facilityId, Funding memory funded) internal {\n        _fund(self, facilityId, funded, 0, false);\n    }\n\n    /// @notice Registers one facility with concurrent cash and PIK curves.\n    function fundMixed(State storage self, uint256 facilityId, MixedFunding memory funded) internal {\n        Funding memory pikTerms = funded.pikTerms;\n        if (\n            !pikTerms.pik || pikTerms.frozenPikBasis != 0 || pikTerms.rateBps == 0 || funded.cashRateBps == 0\n                || uint256(pikTerms.rateBps) + funded.cashRateBps > 10_000 || pikTerms.yearSeconds != 360 days\n        ) revert AccrualLoans_InvalidMixedTerms();\n        _fund(self, facilityId, pikTerms, funded.cashRateBps, true);\n    }\n\n    function _fund(State storage self, uint256 facilityId, Funding memory funded, uint16 cashRateBps, bool mixed)\n        private\n    {\n        if (funded.principal == 0 || funded.principal > MAX_BASIS || funded.balanceCeiling < funded.principal) {\n            revert AccrualLoans_InvalidFunding();\n        }\n        if (funded.frozenPikBasis > MAX_BASIS || (!funded.pik && funded.frozenPikBasis != 0)) {\n            revert AccrualLoans_InvalidFunding();\n        }\n        _validateCeiling(funded.balanceCeiling);\n        _validateSchedule(funded.fundedAt, funded.nextPaymentDue, funded.paymentInterval, funded.maturity);\n        AccrualMath.periodAmount(\n            funded.principal, funded.rateBps, 0, funded.yearSeconds, funded.scale, funded.balanceCeiling\n        );\n        self.book.register(facilityId, funded.keys, funded.fundedAt);\n        Loan storage loan = self.loans[facilityId];\n        loan.principal = funded.principal;\n        loan.balanceCeiling = funded.balanceCeiling;\n        loan.frozenPikBasis = funded.frozenPikBasis == 0 ? funded.principal : funded.frozenPikBasis;\n        loan.nextCapitalization = funded.nextPaymentDue;\n        loan.paymentInterval = funded.paymentInterval;\n        loan.legalMaturity = funded.maturity;\n        loan.lastSettlement = funded.fundedAt;\n        loan.pik = funded.pik;\n        loan.active = true;\n        loan.configured = true;\n        loan.mixed = mixed;\n        loan.mixedCashBasis = mixed ? funded.principal : 0;\n        loan.mixedCashRateBps = cashRateBps;\n        loan.mixedRateStart = mixed ? funded.fundedAt : 0;\n        loan.terms.rateBps = funded.rateBps;\n        loan.terms.yearSeconds = funded.yearSeconds;\n        loan.terms.scale = funded.scale;\n        uint16 workRate = mixed ? funded.rateBps + cashRateBps : funded.rateBps;\n        _replaceWork(self, loan, _weight(funded.pik, workRate, funded.paymentInterval));\n        _newEpoch(loan, funded.fundedAt);\n        _open(self, facilityId, loan, funded.fundedAt);\n    }\n\n    /// @notice Imports one proved opening debt without charging already recognized principal twice.\n    /// @dev Zero new income represents an opening already settled through the legacy system.\n    ///      Active PIK inputs must already identify their next future contractual boundary;\n    ///      zero is permitted for the final maturity stub. Historical capitalization and all\n    ///      balance assertions are proved by the host, not reconstructed from a guessed history.\n    ///      Future increments subtract the original period's cumulative entitlement at cutoff,\n    ///      retaining fractional entitlement instead of restarting its rounding clock.\n    function importOpening(State storage self, uint256 facilityId, Opening memory opening)\n        internal\n        returns (uint256 income)\n    {\n        Loan memory imported = _openingLoan(opening);\n        uint64 at = opening.terms.fundedAt;\n        self.book.register(facilityId, opening.terms.keys, at);\n        self.loans[facilityId] = imported;\n        Loan storage loan = self.loans[facilityId];\n        income = _add(loan.principal, loan.unpaidInterest) - opening.recordedFace;\n        if (income != 0) self.book.creditStoppedCorrection(facilityId, income, at);\n        if (loan.active) {\n            _replaceWork(self, loan, _weight(loan.pik, loan.terms.rateBps, loan.paymentInterval));\n            _open(self, facilityId, loan, at);\n        }\n    }\n\n    /// @dev Constructs the validated opening without mutating the book or its reservation totals.\n    function _openingLoan(Opening memory opening) private pure returns (Loan memory loan) {\n        Funding memory f = opening.terms;\n        uint64 at = f.fundedAt;\n        uint256 face = _add(f.principal, opening.interest);\n        if (face == 0 || face > f.balanceCeiling || opening.recordedFace > face) {\n            revert AccrualLoans_InvalidOpening();\n        }\n        _validateCeiling(f.balanceCeiling);\n        if (f.frozenPikBasis > MAX_BASIS || (!f.pik && f.frozenPikBasis != 0)) {\n            revert AccrualLoans_InvalidOpening();\n        }\n        bool active = !opening.permanentlyStopped && at < f.maturity;\n        if (\n            opening.periodStart > at || opening.periodStart >= f.maturity || f.paymentInterval == 0\n                || (f.nextPaymentDue != 0 && (f.nextPaymentDue > f.maturity || f.paymentInterval > f.nextPaymentDue))\n                || (active && f.pik && f.nextPaymentDue != 0 && f.nextPaymentDue <= at)\n        ) revert AccrualLoans_InvalidOpening();\n        uint256 basis = f.pik && f.frozenPikBasis != 0 ? f.frozenPikBasis : f.principal;\n        uint64 periodEnd =\n            f.pik && f.nextPaymentDue != 0 && f.nextPaymentDue > opening.periodStart ? f.nextPaymentDue : f.maturity;\n        uint64 through = at < periodEnd ? at : periodEnd;\n        uint256 previous = AccrualMath.periodAmount(\n            basis, f.rateBps, through - opening.periodStart, f.yearSeconds, f.scale, type(uint256).max\n        );\n        loan.principal = f.principal;\n        loan.unpaidInterest = opening.interest;\n        loan.balanceCeiling = f.balanceCeiling;\n        loan.frozenPikBasis = basis;\n        loan.nextCapitalization = f.nextPaymentDue;\n        loan.paymentInterval = f.paymentInterval;\n        loan.legalMaturity = f.maturity;\n        loan.lastSettlement = at;\n        loan.pik = f.pik;\n        loan.active = active;\n        loan.configured = true;\n        loan.permanentlyStopped = opening.permanentlyStopped;\n        loan.terms = AccrualSegments.Terms({\n            basis: basis,\n            yearSeconds: f.yearSeconds,\n            scale: f.scale,\n            cap: _add(previous, f.balanceCeiling - face),\n            periodStart: opening.periodStart,\n            periodEnd: periodEnd,\n            maturity: f.maturity,\n            rateBps: f.rateBps\n        });\n    }\n\n    /// @notice Processes at most 32 chronological boundaries and commits partial progress.\n    /// @return work Fixed-capacity result array; only its first processed elements are populated.\n    /// @return processed Number of populated work entries and completed boundaries.\n    /// @return fresh Whether all due boundaries have been processed through at.\n    function checkpoint(State storage self, uint64 at, uint256 maximum)\n        internal\n        returns (LifecycleWork[] memory work, uint256 processed, bool fresh)\n    {\n        if (maximum == 0 || maximum > MAX_BATCH) revert AccrualLoans_BadBatch(maximum);\n        work = new LifecycleWork[](maximum);\n        while (processed < maximum && self.book.schedule.count() != 0) {\n            if (self.book.schedule.peek().deadline > at) break;\n            (uint256 id, uint64 boundary,) = self.book.finishNext(at);\n            Loan storage loan = _loan(self, id);\n            LifecycleWork memory item = _work(id, boundary);\n            (uint256 earned, uint256 cashEarned) = _segmentEarned(loan, boundary);\n            loan.unpaidInterest = _add(loan.unpaidInterest, earned);\n            if (loan.mixed) loan.unpaidCashInterest = _add(loan.unpaidCashInterest, cashEarned);\n            loan.lastSettlement = boundary;\n            if (loan.pik && boundary == loan.nextCapitalization) {\n                _capitalize(loan, item);\n                loan.nextCapitalization = _nextDue(boundary, loan.paymentInterval, loan.legalMaturity);\n                item.nextDue = loan.nextCapitalization;\n                if (boundary < loan.legalMaturity) _newEpoch(loan, boundary);\n            }\n            if (boundary == loan.legalMaturity) {\n                _deactivate(self, loan);\n                item.stopped = true;\n            } else {\n                _open(self, id, loan, boundary);\n            }\n            work[processed++] = item;\n        }\n        fresh = self.book.schedule.count() == 0 || self.book.schedule.peek().deadline > at;\n        if (fresh) self.book.checkpoint(at);\n    }\n\n    /// @notice Aligns exact contractual debt, returns native receipt work, then resumes forward.\n    /// @dev The host proves the original attested legs and measured custody. A PIK principal leg\n    ///      can discharge uncapitalized interest after capitalized principal; its interest leg is\n    ///      zero. Cash legs discharge their own separate balances. Only the sum must lie on-grid.\n    function repay(State storage self, uint256 facilityId, uint256 principalLeg, uint256 interestLeg, uint64 at)\n        internal\n        returns (LifecycleWork memory work)\n    {\n        Loan storage loan = _loan(self, facilityId);\n        uint256 paid = _add(principalLeg, interestLeg);\n        if (paid == 0 || paid % loan.terms.scale != 0) revert AccrualLoans_BadPayment();\n        if (loan.pik && !loan.mixed && interestLeg != 0) revert AccrualLoans_PikInterestLeg();\n        bool capPaused = loan.mixed ? _mixedCapReached(loan, at) : _capReached(loan, at);\n        work = _close(self, facilityId, loan, at);\n        if (loan.mixed) {\n            uint256 unpaidPik = loan.unpaidInterest - loan.unpaidCashInterest;\n            if (principalLeg > _add(loan.principal, unpaidPik) || interestLeg > loan.unpaidCashInterest) {\n                revert AccrualLoans_PaymentAboveDebt();\n            }\n            work.principalReduction = principalLeg < loan.principal ? principalLeg : loan.principal;\n            uint256 pikReduction = principalLeg - work.principalReduction;\n            work.interestReduction = pikReduction + interestLeg;\n            loan.principal -= work.principalReduction;\n            loan.unpaidInterest -= work.interestReduction;\n            loan.unpaidCashInterest -= interestLeg;\n        } else if (loan.pik) {\n            if (principalLeg > _add(loan.principal, loan.unpaidInterest)) revert AccrualLoans_PaymentAboveDebt();\n            work.principalReduction = principalLeg < loan.principal ? principalLeg : loan.principal;\n            work.interestReduction = principalLeg - work.principalReduction;\n        } else {\n            if (principalLeg > loan.principal || interestLeg > loan.unpaidInterest) {\n                revert AccrualLoans_PaymentAboveDebt();\n            }\n            work.principalReduction = principalLeg;\n            work.interestReduction = interestLeg;\n        }\n        if (!loan.mixed) {\n            loan.principal -= work.principalReduction;\n            loan.unpaidInterest -= work.interestReduction;\n        }\n        if (loan.principal == 0 && loan.unpaidInterest == 0) {\n            _deactivate(self, loan);\n            loan.permanentlyStopped = true;\n            work.stopped = true;\n            work.repaid = true;\n        } else if (loan.active && at < loan.legalMaturity) {\n            // Replenishing a binding cap starts now; it cannot backfill clipped historical time.\n            // Cash principal changes rebase only prospectively. Otherwise keep the original\n            // epoch/curve, especially for a partial PIK principal payment in a frozen period.\n            if (capPaused || (!loan.pik && principalLeg != 0) || at >= loan.terms.periodEnd) {\n                _newEpoch(loan, at);\n            } else if (loan.mixed && work.principalReduction != 0) {\n                _rollMixedRates(loan, at);\n                loan.mixedCashBasis = loan.principal;\n                loan.terms.cap = _add(loan.terms.cap, paid);\n            } else {\n                // No clipped time exists before the cap is reached. Retain the same cumulative\n                // curve and expand its ceiling by the proved debt repayment instead of losing\n                // the original period's fractional entitlement through an unnecessary restart.\n                loan.terms.cap = _add(loan.terms.cap, paid);\n            }\n            _open(self, facilityId, loan, at);\n        } else if (at >= loan.legalMaturity) {\n            _deactivate(self, loan);\n            work.stopped = true;\n        }\n    }\n\n    /// @notice Applies authenticated forward terms after closing the old arithmetic at at.\n    /// @dev The signed nextPaymentDue replaces the future PIK capitalization date. No principal\n    ///      reclassification or PIK rebasing occurs merely because this amendment was signed.\n    function amend(State storage self, uint256 facilityId, Amendment memory changed, uint64 at)\n        internal\n        returns (LifecycleWork memory work)\n    {\n        Loan storage loan = _loan(self, facilityId);\n        if (loan.mixed) revert AccrualLoans_MixedLifecycleRequired(facilityId);\n        if (loan.permanentlyStopped) revert AccrualLoans_Inactive(facilityId);\n        _validateCeiling(changed.balanceCeiling);\n        _validateSchedule(at, changed.nextPaymentDue, changed.paymentInterval, changed.maturity);\n        AccrualMath.periodAmount(loan.terms.basis, changed.rateBps, 0, changed.yearSeconds, loan.terms.scale, 0);\n        uint64 previousDue = loan.nextCapitalization;\n        work = _close(self, facilityId, loan, at);\n        _replaceWork(self, loan, _weight(loan.pik, changed.rateBps, changed.paymentInterval));\n        loan.active = true;\n        work.previousDue = previousDue;\n        work.nextDue = changed.nextPaymentDue;\n        loan.nextCapitalization = changed.nextPaymentDue;\n        loan.paymentInterval = changed.paymentInterval;\n        loan.legalMaturity = changed.maturity;\n        loan.balanceCeiling = changed.balanceCeiling;\n        loan.terms.rateBps = changed.rateBps;\n        loan.terms.yearSeconds = changed.yearSeconds;\n        _newEpoch(loan, at);\n        _open(self, facilityId, loan, at);\n    }\n\n    /// @notice Applies authenticated prospective rates and PIK dates to a mixed facility.\n    function amendMixed(State storage self, uint256 facilityId, MixedAmendment memory changed, uint64 at)\n        internal\n        returns (LifecycleWork memory work)\n    {\n        Loan storage loan = _loan(self, facilityId);\n        Amendment memory pikTerms = changed.pikTerms;\n        if (!loan.mixed) revert AccrualLoans_MixedLifecycleRequired(facilityId);\n        if (\n            loan.permanentlyStopped || pikTerms.rateBps == 0 || changed.cashRateBps == 0\n                || uint256(pikTerms.rateBps) + changed.cashRateBps > 10_000 || pikTerms.yearSeconds != 360 days\n        ) {\n            if (loan.permanentlyStopped) revert AccrualLoans_Inactive(facilityId);\n            revert AccrualLoans_InvalidMixedTerms();\n        }\n        _validateCeiling(pikTerms.balanceCeiling);\n        _validateSchedule(at, pikTerms.nextPaymentDue, pikTerms.paymentInterval, pikTerms.maturity);\n        AccrualMath.periodAmount(loan.frozenPikBasis, pikTerms.rateBps, 0, pikTerms.yearSeconds, loan.terms.scale, 0);\n        AccrualMath.periodAmount(loan.principal, changed.cashRateBps, 0, pikTerms.yearSeconds, loan.terms.scale, 0);\n        uint64 previousDue = loan.nextCapitalization;\n        work = _close(self, facilityId, loan, at);\n        _replaceWork(self, loan, _weight(true, pikTerms.rateBps + changed.cashRateBps, pikTerms.paymentInterval));\n        loan.active = true;\n        work.previousDue = previousDue;\n        work.nextDue = pikTerms.nextPaymentDue;\n        loan.nextCapitalization = pikTerms.nextPaymentDue;\n        loan.paymentInterval = pikTerms.paymentInterval;\n        loan.legalMaturity = pikTerms.maturity;\n        loan.balanceCeiling = pikTerms.balanceCeiling;\n        loan.terms.rateBps = pikTerms.rateBps;\n        loan.terms.yearSeconds = pikTerms.yearSeconds;\n        loan.mixedCashRateBps = changed.cashRateBps;\n        _newEpoch(loan, at);\n        _open(self, facilityId, loan, at);\n    }\n\n    /// @notice Aligns and permanently stops accrual before the host's default/acceleration action.\n    /// @dev The host posts the returned face and resolves any rounding loss before default snapshots.\n    function stop(State storage self, uint256 facilityId, uint64 at) internal returns (LifecycleWork memory work) {\n        Loan storage loan = _loan(self, facilityId);\n        work = _close(self, facilityId, loan, at);\n        _deactivate(self, loan);\n        loan.permanentlyStopped = true;\n        work.stopped = true;\n    }\n\n    /// @notice Services signed PIK dates that have no positive queued interest work.\n    /// @dev Scheduled loans, cash loans, inactive loans and future dormant dates are unchanged.\n    ///      Existing unpaid PIK is capitalized once; only proven zero-income successors are\n    ///      skipped arithmetically. The shared Book checkpoint stores already-visible growth\n    ///      without adding entitlement, posting, closing/reopening a segment or minting yield.\n    ///      The host applies only a nonzero later signed nextDue to its bridge and uses legal\n    ///      maturity as the balloon deadline once no signed capitalization boundary remains.\n    function serviceDormant(State storage self, uint256 facilityId, uint64 at)\n        internal\n        returns (LifecycleWork memory work)\n    {\n        Loan storage loan = _loan(self, facilityId);\n        self.book.requireFresh(at);\n        work = _work(facilityId, at);\n        if (self.book.entries[facilityId].scheduled || !loan.active || !loan.pik) return work;\n        if (at < loan.legalMaturity && (loan.nextCapitalization == 0 || loan.nextCapitalization > at)) return work;\n        self.book.checkpoint(at);\n        _settleDormantPik(loan, work, at);\n        loan.lastSettlement = at;\n        if (at >= loan.legalMaturity) {\n            _deactivate(self, loan);\n            work.stopped = true;\n        }\n    }\n\n    /// @notice Takes already-recognized posting work without resetting a contractual curve.\n    function post(State storage self, uint256 facilityId, uint64 at) internal returns (uint256 amount) {\n        _loan(self, facilityId);\n        self.book.requireFresh(at);\n        amount = self.book.takePosting(facilityId, at);\n    }\n\n    /// @notice Retires a completely paid, stopped, posted facility while retaining its known-ID tombstone.\n    function retire(State storage self, uint256 facilityId, uint64 at) internal {\n        Loan storage loan = _loan(self, facilityId);\n        if (loan.active || loan.principal != 0 || loan.unpaidInterest != 0) revert AccrualLoans_Unsettled(facilityId);\n        self.book.retire(facilityId, at);\n    }\n\n    /// @notice Exact contractual face through the book's coherent current frontier, in O(1).\n    /// @dev This is not a replacement for the booked accounting carrier used by reserve NAV.\n    function loanFace(State storage self, uint256 facilityId, uint64 at)\n        internal\n        view\n        returns (uint256 principal, uint256 interest, uint64 accruedThrough)\n    {\n        Loan storage loan = _loan(self, facilityId);\n        accruedThrough = self.book.snapshot(at).accruedThrough;\n        principal = loan.principal;\n        interest = loan.unpaidInterest;\n        if (self.book.entries[facilityId].scheduled) {\n            (uint256 earned,) = _segmentEarned(loan, accruedThrough);\n            interest = _add(interest, earned);\n        }\n        if (\n            loan.active && loan.pik && !self.book.entries[facilityId].scheduled && loan.nextCapitalization != 0\n                && loan.nextCapitalization <= accruedThrough && loan.nextCapitalization <= loan.legalMaturity\n        ) {\n            if (loan.mixed) {\n                uint256 cashInterest = loan.unpaidCashInterest;\n                principal = _add(principal, interest - cashInterest);\n                interest = cashInterest;\n            } else {\n                principal = _add(principal, interest);\n                interest = 0;\n            }\n        }\n    }\n\n    /// @notice Current unpaid cash and PIK interest through the coherent Book frontier.\n    function loanInterestLegs(State storage self, uint256 facilityId, uint64 at)\n        internal\n        view\n        returns (uint256 cash, uint256 pik, uint64 accruedThrough)\n    {\n        Loan storage loan = _loan(self, facilityId);\n        accruedThrough = self.book.snapshot(at).accruedThrough;\n        cash = loan.unpaidCashInterest;\n        uint256 total = loan.unpaidInterest;\n        if (self.book.entries[facilityId].scheduled) {\n            (uint256 earned, uint256 cashEarned) = _segmentEarned(loan, accruedThrough);\n            total = _add(total, earned);\n            cash = _add(cash, cashEarned);\n        }\n        pik = total - cash;\n        // A binding ceiling can leave a live mixed loan unscheduled before its signed PIK\n        // date. The servicing path capitalizes that stored PIK in O(1) when the date arrives,\n        // and loanFace already presents the same debt as principal. Mirror that virtual\n        // classification here so callers cannot add a stale PIK-interest leg to a principal\n        // balance that already includes it.\n        if (\n            loan.mixed && loan.active && !self.book.entries[facilityId].scheduled && loan.nextCapitalization != 0\n                && loan.nextCapitalization <= accruedThrough && loan.nextCapitalization <= loan.legalMaturity\n        ) pik = 0;\n    }\n\n    /// @dev Stops the local interpolation, aligns the canonical contribution and consumes posting.\n    function _close(State storage self, uint256 id, Loan storage loan, uint64 at)\n        private\n        returns (LifecycleWork memory work)\n    {\n        self.book.requireFresh(at);\n        work = _work(id, at);\n        if (loan.closureNonce == type(uint64).max) revert AccrualLoans_Overflow();\n        work.closureNonce = ++loan.closureNonce;\n        if (self.book.entries[id].scheduled) {\n            self.book.stop(id, at);\n            uint256 recognized = self.book.earned(id, at) - loan.segmentBookBase;\n            (uint256 canonical, uint256 cashCanonical) = _segmentEarned(loan, at);\n            if (canonical > recognized) {\n                work.positiveCorrection = canonical - recognized;\n                if (work.positiveCorrection > loan.terms.scale) {\n                    revert AccrualLoans_CorrectionOutsideBound(work.positiveCorrection, loan.terms.scale);\n                }\n                self.book.creditStoppedCorrection(id, work.positiveCorrection, at);\n            } else {\n                work.roundingLoss = recognized - canonical;\n                if (work.roundingLoss >= loan.terms.scale) {\n                    revert AccrualLoans_CorrectionOutsideBound(work.roundingLoss, loan.terms.scale);\n                }\n            }\n            loan.unpaidInterest = _add(loan.unpaidInterest, canonical);\n            if (loan.mixed) loan.unpaidCashInterest = _add(loan.unpaidCashInterest, cashCanonical);\n        } else if (loan.active) {\n            _settleDormantPik(loan, work, at);\n        }\n        work.posting = self.book.takePosting(id, at);\n        loan.lastSettlement = at;\n    }\n\n    /// @dev Opens only useful positive-entitlement work; zero-rate/cap-paused periods do not loop.\n    function _open(State storage self, uint256 id, Loan storage loan, uint64 at) private {\n        if (!loan.active || at >= loan.legalMaturity) return;\n        if (loan.mixed) {\n            MixedSegment memory mixed = _planMixed(loan, at);\n            if (mixed.end == at) return;\n            loan.segmentBookBase = self.book.earned(id, at);\n            loan.segmentCumulativeStart = mixed.cumulativeStart;\n            loan.mixedCashSegmentCumulativeStart = mixed.cashCumulativeStart;\n            self.book.open(id, mixed.amount, at, mixed.end);\n            return;\n        }\n        if (loan.terms.rateBps == 0 || (!loan.pik && loan.terms.basis == 0)) return;\n        // An imported zero-basis PIK period can still capitalize existing unpaid interest,\n        // creating a positive basis at its next signed date. Keep that boundary scheduled.\n        // A dormant PIK period is skipped only if both its remaining entitlement and every\n        // unchanged successor are zero. The prospective next basis includes existing unpaid\n        // income, so a pending capitalization that enables a positive next coupon is scheduled.\n        // A longer first period is not mistaken for a zero regular short coupon.\n        if (loan.pik) {\n            uint256 remaining = AccrualSegments.cumulative(loan.terms, loan.terms.periodEnd)\n                - AccrualSegments.cumulative(loan.terms, at);\n            uint256 nextBasis = _add(_add(loan.principal, loan.unpaidInterest), remaining);\n            uint256 room = nextBasis < loan.balanceCeiling ? loan.balanceCeiling - nextBasis : 0;\n            if (\n                remaining == 0\n                    && AccrualMath.periodAmount(\n                        nextBasis, loan.terms.rateBps, loan.paymentInterval, loan.terms.yearSeconds, loan.terms.scale, room\n                    ) == 0\n            ) return;\n        }\n        if (!loan.pik && AccrualSegments.cumulative(loan.terms, loan.legalMaturity) == 0) return;\n        AccrualSegments.Segment memory segment = AccrualSegments.plan(loan.terms, at);\n        if (segment.end == at) return;\n        loan.segmentBookBase = self.book.earned(id, at);\n        loan.segmentCumulativeStart = segment.cumulativeStart;\n        self.book.open(id, segment.amount, at, segment.end);\n    }\n\n    /// @dev A new arithmetic epoch preserves the signed PIK basis while refreshing available room.\n    function _newEpoch(Loan storage loan, uint64 at) private {\n        loan.terms.basis = loan.pik ? loan.frozenPikBasis : loan.principal;\n        loan.terms.periodStart = at;\n        loan.terms.periodEnd = loan.pik && loan.nextCapitalization != 0 ? loan.nextCapitalization : loan.legalMaturity;\n        loan.terms.maturity = loan.legalMaturity;\n        uint256 face = _add(loan.principal, loan.unpaidInterest);\n        loan.terms.cap = face < loan.balanceCeiling ? loan.balanceCeiling - face : 0;\n        if (loan.mixed) {\n            loan.mixedCashBasis = loan.principal;\n            loan.mixedCashCarry = 0;\n            loan.mixedPikCarry = 0;\n            loan.mixedCashRemainder = 0;\n            loan.mixedPikRemainder = 0;\n            loan.mixedRateStart = at;\n            loan.mixedCashSegmentCumulativeStart = 0;\n        }\n    }\n\n    /// @dev A paused cap or zero-rate interval has no unseen interest recurrence. Capitalize its\n    ///      existing PIK U once, then skip only further zero-income dates arithmetically in O(1).\n    function _settleDormantPik(Loan storage loan, LifecycleWork memory work, uint64 at) private {\n        uint64 due = loan.nextCapitalization;\n        if (!loan.pik || due == 0 || due > at || due > loan.legalMaturity) return;\n        _capitalize(loan, work);\n        uint64 through = at < loan.legalMaturity ? at : loan.legalMaturity;\n        uint256 count = uint256(through - due) / loan.paymentInterval + 1;\n        uint256 remaining = uint256(loan.legalMaturity - due) / loan.paymentInterval;\n        loan.nextCapitalization = count > remaining ? 0 : due + uint64(count * loan.paymentInterval);\n        work.nextDue = loan.nextCapitalization;\n    }\n\n    /// @dev Reclassifies already accrued PIK debt; does not recognize/post/mint it again.\n    function _capitalize(Loan storage loan, LifecycleWork memory work) private {\n        work.previousDue = loan.nextCapitalization;\n        work.capitalized = loan.mixed ? loan.unpaidInterest - loan.unpaidCashInterest : loan.unpaidInterest;\n        loan.principal = _add(loan.principal, work.capitalized);\n        loan.unpaidInterest = loan.mixed ? loan.unpaidCashInterest : 0;\n        loan.frozenPikBasis = loan.principal;\n    }\n\n    /// @notice Canonical current-segment entitlement used by the native rounding preparer.\n    function canonicalSegment(Loan storage loan, uint64 at) internal view returns (uint256 total, uint256 cash) {\n        return _segmentEarned(loan, at);\n    }\n\n    function _segmentEarned(Loan storage loan, uint64 at) private view returns (uint256 total, uint256 cash) {\n        if (!loan.mixed) {\n            total = AccrualSegments.cumulative(loan.terms, at) - loan.segmentCumulativeStart;\n            return (total, 0);\n        }\n        (uint256 cumulative, uint256 cashCumulative) = _mixedCumulative(loan, at);\n        total = cumulative - loan.segmentCumulativeStart;\n        cash = cashCumulative - loan.mixedCashSegmentCumulativeStart;\n    }\n\n    /// @dev Plans one aggregate Book segment while retaining separate contractual leg arithmetic.\n    function _planMixed(Loan storage loan, uint64 at) private view returns (MixedSegment memory segment) {\n        uint64 effectiveEnd = loan.terms.periodEnd < loan.legalMaturity ? loan.terms.periodEnd : loan.legalMaturity;\n        if (at < loan.terms.periodStart || at > effectiveEnd) revert AccrualLoans_InvalidSchedule();\n        (segment.cumulativeStart, segment.cashCumulativeStart) = _mixedCumulative(loan, at);\n        segment.end = at;\n        uint256 gridCap = loan.terms.cap - loan.terms.cap % loan.terms.scale;\n        if (at == effectiveEnd || segment.cumulativeStart == gridCap) return segment;\n\n        uint64 technicalRemaining =\n            AccrualSegments.MAX_SEGMENT_SECONDS - (at - loan.terms.periodStart) % AccrualSegments.MAX_SEGMENT_SECONDS;\n        uint64 remaining = effectiveEnd - at;\n        segment.end = at + (remaining < technicalRemaining ? remaining : technicalRemaining);\n\n        (uint256 finalCumulative,) = _mixedCumulative(loan, effectiveEnd);\n        if (finalCumulative == gridCap) {\n            uint64 low = at + 1;\n            uint64 high = effectiveEnd;\n            while (low < high) {\n                uint64 middle = low + (high - low) / 2;\n                (uint256 value,) = _mixedCumulative(loan, middle);\n                if (value >= gridCap) high = middle;\n                else low = middle + 1;\n            }\n            uint64 capBoundary = low;\n            if (capBoundary - at > 1) --capBoundary;\n            if (capBoundary < segment.end) segment.end = capBoundary;\n        }\n        (uint256 cumulativeEnd,) = _mixedCumulative(loan, segment.end);\n        segment.amount = cumulativeEnd - segment.cumulativeStart;\n    }\n\n    /// @dev Aggregate grid rounding occurs once; any cross-leg grid remainder belongs to PIK.\n    function _mixedCumulative(Loan storage loan, uint64 at) private view returns (uint256 total, uint256 cash) {\n        (uint256 cashWhole, uint256 cashRemainder) = _legPreview(\n            loan.mixedCashCarry,\n            loan.mixedCashRemainder,\n            loan.mixedCashBasis,\n            loan.mixedCashRateBps,\n            loan.mixedRateStart,\n            at,\n            loan.terms.yearSeconds\n        );\n        (uint256 pikWhole, uint256 pikRemainder) = _legPreview(\n            loan.mixedPikCarry,\n            loan.mixedPikRemainder,\n            loan.frozenPikBasis,\n            loan.terms.rateBps,\n            loan.mixedRateStart,\n            at,\n            loan.terms.yearSeconds\n        );\n        uint256 raw = _add(cashWhole, pikWhole);\n        // The two legs share one Actual/360 denominator. Carry their fractional wei into the\n        // aggregate before applying the native asset grid; otherwise independently flooring\n        // each leg can lose the aggregate carry and make endpoint interpolation exceed the\n        // canonical curve by one whole grid unit.\n        uint256 denominator = 10_000 * loan.terms.yearSeconds;\n        if (cashRemainder >= denominator - pikRemainder) raw = _add(raw, 1);\n        if (raw > loan.terms.cap) raw = loan.terms.cap;\n        total = raw - raw % loan.terms.scale;\n        cash = cashWhole - cashWhole % loan.terms.scale;\n        if (cash > total) cash = total;\n    }\n\n    /// @dev Carries exact rational remainders when a principal change alters only the cash basis.\n    function _rollMixedRates(Loan storage loan, uint64 at) private {\n        (loan.mixedCashCarry, loan.mixedCashRemainder) = _legPreview(\n            loan.mixedCashCarry,\n            loan.mixedCashRemainder,\n            loan.mixedCashBasis,\n            loan.mixedCashRateBps,\n            loan.mixedRateStart,\n            at,\n            loan.terms.yearSeconds\n        );\n        (loan.mixedPikCarry, loan.mixedPikRemainder) = _legPreview(\n            loan.mixedPikCarry,\n            loan.mixedPikRemainder,\n            loan.frozenPikBasis,\n            loan.terms.rateBps,\n            loan.mixedRateStart,\n            at,\n            loan.terms.yearSeconds\n        );\n        loan.mixedRateStart = at;\n    }\n\n    function _legPreview(\n        uint256 carry,\n        uint256 remainder,\n        uint256 basis,\n        uint16 rateBps,\n        uint64 start,\n        uint64 at,\n        uint256 yearSeconds\n    ) private pure returns (uint256 whole, uint256 nextRemainder) {\n        if (at < start) revert AccrualLoans_InvalidSchedule();\n        uint256 denominator = 10_000 * yearSeconds;\n        uint256 coefficient = basis * rateBps;\n        uint256 elapsed = at - start;\n        uint256 quotient = Math.mulDiv(coefficient, elapsed, denominator);\n        nextRemainder = mulmod(coefficient, elapsed, denominator) + remainder;\n        if (nextRemainder >= denominator) {\n            nextRemainder -= denominator;\n            quotient = _add(quotient, 1);\n        }\n        whole = _add(carry, quotient);\n    }\n\n    function _mixedCapReached(Loan storage loan, uint64 at) private view returns (bool) {\n        uint64 end = loan.terms.periodEnd < loan.legalMaturity ? loan.terms.periodEnd : loan.legalMaturity;\n        uint64 through = at < end ? at : end;\n        uint256 gridCap = loan.terms.cap - loan.terms.cap % loan.terms.scale;\n        (uint256 current,) = _mixedCumulative(loan, through);\n        if (current != gridCap) return false;\n        (uint256 finalAmount,) = _mixedCumulative(loan, end);\n        return finalAmount == gridCap;\n    }\n\n    function _capReached(Loan storage loan, uint64 at) private view returns (bool) {\n        AccrualSegments.Segment memory prior = AccrualSegments.plan(loan.terms, loan.terms.periodStart);\n        return prior.capReachable && prior.capHit <= at;\n    }\n\n    /// @dev Returns only a real next contractual capitalization date, never inventing maturity compounding.\n    function _nextDue(uint64 previous, uint64 interval, uint64 maturity) private pure returns (uint64) {\n        return interval <= maturity - previous ? previous + interval : 0;\n    }\n\n    /// @dev Reservations persist during cap pauses and are released only on permanent stopping.\n    function _deactivate(State storage self, Loan storage loan) private {\n        if (loan.active) {\n            _replaceWork(self, loan, 0);\n            loan.active = false;\n        }\n    }\n\n    /// @dev Conservative autonomous annual work plus phase/technical/cap allowance, per active loan.\n    function _weight(bool pik, uint16 rateBps, uint64 interval) private pure returns (uint256) {\n        if (rateBps == 0) return 0;\n        return pik ? YEAR / interval + (YEAR % interval == 0 ? 0 : 1) + 4 : 4;\n    }\n\n    /// @dev Replacement is atomic: a rejected amendment preserves the prior reservation and terms.\n    function _replaceWork(State storage self, Loan storage loan, uint256 replacement) private {\n        uint256 requested = self.annualWork - loan.workWeight + replacement;\n        // An upgraded historical book may already exceed the newly funded keeper envelope.\n        // Refusing a strict reduction would trap that book above the cap forever: even default,\n        // repayment or a safer amendment could not release its old reservation. While over cap,\n        // admit only a replacement that lowers this loan's contribution. New admissions,\n        // unchanged schedules and increases continue to fail until the portfolio is back inside.\n        if (requested > MAX_ANNUAL_WORK && replacement >= loan.workWeight) {\n            revert AccrualLoans_WorkCapacity(requested);\n        }\n        self.annualWork = requested;\n        loan.workWeight = replacement;\n    }\n\n    /// @dev Validates signed funding/amendment dates without imposing a minimum individual interval.\n    function _validateSchedule(uint64 at, uint64 due, uint64 interval, uint64 maturity) private pure {\n        if (interval == 0 || due <= at || due > maturity || interval > due || maturity <= at) {\n            revert AccrualLoans_InvalidSchedule();\n        }\n    }\n\n    /// @dev Every future PIK basis must remain inside the already-admitted math domain.\n    function _validateCeiling(uint256 ceiling) private pure {\n        if (ceiling > MAX_BASIS) revert AccrualLoans_InvalidCeiling(ceiling);\n    }\n\n    /// @dev Lookup is separate from Book registration so retired contractual metadata remains readable.\n    function _loan(State storage self, uint256 facilityId) private view returns (Loan storage loan) {\n        loan = self.loans[facilityId];\n        if (!loan.configured) revert AccrualLoans_Unknown(facilityId);\n    }\n\n    /// @dev Initializes a result without any externally supplied posting or correction amount.\n    function _work(uint256 id, uint64 at) private pure returns (LifecycleWork memory work) {\n        work.facilityId = id;\n        work.at = at;\n    }\n\n    /// @dev Uses a stable named error instead of a generic arithmetic panic at capacity bounds.\n    function _add(uint256 first, uint256 second) private pure returns (uint256) {\n        if (second > type(uint256).max - first) revert AccrualLoans_Overflow();\n        return first + second;\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/Strings.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/Strings.sol)\n\npragma solidity ^0.8.20;\n\nimport {Math} from \"./math/Math.sol\";\nimport {SafeCast} from \"./math/SafeCast.sol\";\nimport {SignedMath} from \"./math/SignedMath.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n    using SafeCast for *;\n\n    bytes16 private constant HEX_DIGITS = \"0123456789abcdef\";\n    uint8 private constant ADDRESS_LENGTH = 20;\n    uint256 private constant SPECIAL_CHARS_LOOKUP =\n        (1 << 0x08) | // backspace\n            (1 << 0x09) | // tab\n            (1 << 0x0a) | // newline\n            (1 << 0x0c) | // form feed\n            (1 << 0x0d) | // carriage return\n            (1 << 0x22) | // double quote\n            (1 << 0x5c); // backslash\n\n    /**\n     * @dev The `value` string doesn't fit in the specified `length`.\n     */\n    error StringsInsufficientHexLength(uint256 value, uint256 length);\n\n    /**\n     * @dev The string being parsed contains characters that are not in scope of the given base.\n     */\n    error StringsInvalidChar();\n\n    /**\n     * @dev The string being parsed is not a properly formatted address.\n     */\n    error StringsInvalidAddressFormat();\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n     */\n    function toString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            uint256 length = Math.log10(value) + 1;\n            string memory buffer = new string(length);\n            uint256 ptr;\n            assembly (\"memory-safe\") {\n                ptr := add(add(buffer, 0x20), length)\n            }\n            while (true) {\n                ptr--;\n                assembly (\"memory-safe\") {\n                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))\n                }\n                value /= 10;\n                if (value == 0) break;\n            }\n            return buffer;\n        }\n    }\n\n    /**\n     * @dev Converts a `int256` to its ASCII `string` decimal representation.\n     */\n    function toStringSigned(int256 value) internal pure returns (string memory) {\n        return string.concat(value < 0 ? \"-\" : \"\", toString(SignedMath.abs(value)));\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n     */\n    function toHexString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            return toHexString(value, Math.log256(value) + 1);\n        }\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n     */\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n        uint256 localValue = value;\n        bytes memory buffer = new bytes(2 * length + 2);\n        buffer[0] = \"0\";\n        buffer[1] = \"x\";\n        for (uint256 i = 2 * length + 1; i > 1; --i) {\n            buffer[i] = HEX_DIGITS[localValue & 0xf];\n            localValue >>= 4;\n        }\n        if (localValue != 0) {\n            revert StringsInsufficientHexLength(value, length);\n        }\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal\n     * representation.\n     */\n    function toHexString(address addr) internal pure returns (string memory) {\n        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal\n     * representation, according to EIP-55.\n     */\n    function toChecksumHexString(address addr) internal pure returns (string memory) {\n        bytes memory buffer = bytes(toHexString(addr));\n\n        // hash the hex part of buffer (skip length + 2 bytes, length 40)\n        uint256 hashValue;\n        assembly (\"memory-safe\") {\n            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))\n        }\n\n        for (uint256 i = 41; i > 1; --i) {\n            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)\n            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {\n                // case shift by xoring with 0x20\n                buffer[i] ^= 0x20;\n            }\n            hashValue >>= 4;\n        }\n        return string(buffer);\n    }\n\n    /**\n     * @dev Returns true if the two strings are equal.\n     */\n    function equal(string memory a, string memory b) internal pure returns (bool) {\n        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));\n    }\n\n    /**\n     * @dev Parse a decimal string and returns the value as a `uint256`.\n     *\n     * Requirements:\n     * - The string must be formatted as `[0-9]*`\n     * - The result must fit into an `uint256` type\n     */\n    function parseUint(string memory input) internal pure returns (uint256) {\n        return parseUint(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and\n     * `end` (excluded).\n     *\n     * Requirements:\n     * - The substring must be formatted as `[0-9]*`\n     * - The result must fit into an `uint256` type\n     */\n    function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {\n        (bool success, uint256 value) = tryParseUint(input, begin, end);\n        if (!success) revert StringsInvalidChar();\n        return value;\n    }\n\n    /**\n     * @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.\n     *\n     * NOTE: This function will revert if the result does not fit in a `uint256`.\n     */\n    function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {\n        return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid\n     * character.\n     *\n     * NOTE: This function will revert if the result does not fit in a `uint256`.\n     */\n    function tryParseUint(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) internal pure returns (bool success, uint256 value) {\n        if (end > bytes(input).length || begin > end) return (false, 0);\n        return _tryParseUintUncheckedBounds(input, begin, end);\n    }\n\n    /**\n     * @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that\n     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.\n     */\n    function _tryParseUintUncheckedBounds(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) private pure returns (bool success, uint256 value) {\n        bytes memory buffer = bytes(input);\n\n        uint256 result = 0;\n        for (uint256 i = begin; i < end; ++i) {\n            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));\n            if (chr > 9) return (false, 0);\n            result *= 10;\n            result += chr;\n        }\n        return (true, result);\n    }\n\n    /**\n     * @dev Parse a decimal string and returns the value as a `int256`.\n     *\n     * Requirements:\n     * - The string must be formatted as `[-+]?[0-9]*`\n     * - The result must fit in an `int256` type.\n     */\n    function parseInt(string memory input) internal pure returns (int256) {\n        return parseInt(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and\n     * `end` (excluded).\n     *\n     * Requirements:\n     * - The substring must be formatted as `[-+]?[0-9]*`\n     * - The result must fit in an `int256` type.\n     */\n    function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {\n        (bool success, int256 value) = tryParseInt(input, begin, end);\n        if (!success) revert StringsInvalidChar();\n        return value;\n    }\n\n    /**\n     * @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if\n     * the result does not fit in a `int256`.\n     *\n     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.\n     */\n    function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {\n        return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);\n    }\n\n    uint256 private constant ABS_MIN_INT256 = 2 ** 255;\n\n    /**\n     * @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid\n     * character or if the result does not fit in a `int256`.\n     *\n     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.\n     */\n    function tryParseInt(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) internal pure returns (bool success, int256 value) {\n        if (end > bytes(input).length || begin > end) return (false, 0);\n        return _tryParseIntUncheckedBounds(input, begin, end);\n    }\n\n    /**\n     * @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that\n     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.\n     */\n    function _tryParseIntUncheckedBounds(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) private pure returns (bool success, int256 value) {\n        bytes memory buffer = bytes(input);\n\n        // Check presence of a negative sign.\n        bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty\n        bool positiveSign = sign == bytes1(\"+\");\n        bool negativeSign = sign == bytes1(\"-\");\n        uint256 offset = (positiveSign || negativeSign).toUint();\n\n        (bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);\n\n        if (absSuccess && absValue < ABS_MIN_INT256) {\n            return (true, negativeSign ? -int256(absValue) : int256(absValue));\n        } else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {\n            return (true, type(int256).min);\n        } else return (false, 0);\n    }\n\n    /**\n     * @dev Parse a hexadecimal string (with or without \"0x\" prefix), and returns the value as a `uint256`.\n     *\n     * Requirements:\n     * - The string must be formatted as `(0x)?[0-9a-fA-F]*`\n     * - The result must fit in an `uint256` type.\n     */\n    function parseHexUint(string memory input) internal pure returns (uint256) {\n        return parseHexUint(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and\n     * `end` (excluded).\n     *\n     * Requirements:\n     * - The substring must be formatted as `(0x)?[0-9a-fA-F]*`\n     * - The result must fit in an `uint256` type.\n     */\n    function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {\n        (bool success, uint256 value) = tryParseHexUint(input, begin, end);\n        if (!success) revert StringsInvalidChar();\n        return value;\n    }\n\n    /**\n     * @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.\n     *\n     * NOTE: This function will revert if the result does not fit in a `uint256`.\n     */\n    function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {\n        return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an\n     * invalid character.\n     *\n     * NOTE: This function will revert if the result does not fit in a `uint256`.\n     */\n    function tryParseHexUint(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) internal pure returns (bool success, uint256 value) {\n        if (end > bytes(input).length || begin > end) return (false, 0);\n        return _tryParseHexUintUncheckedBounds(input, begin, end);\n    }\n\n    /**\n     * @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that\n     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.\n     */\n    function _tryParseHexUintUncheckedBounds(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) private pure returns (bool success, uint256 value) {\n        bytes memory buffer = bytes(input);\n\n        // skip 0x prefix if present\n        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2(\"0x\"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty\n        uint256 offset = hasPrefix.toUint() * 2;\n\n        uint256 result = 0;\n        for (uint256 i = begin + offset; i < end; ++i) {\n            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));\n            if (chr > 15) return (false, 0);\n            result *= 16;\n            unchecked {\n                // Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).\n                // This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.\n                result += chr;\n            }\n        }\n        return (true, result);\n    }\n\n    /**\n     * @dev Parse a hexadecimal string (with or without \"0x\" prefix), and returns the value as an `address`.\n     *\n     * Requirements:\n     * - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`\n     */\n    function parseAddress(string memory input) internal pure returns (address) {\n        return parseAddress(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and\n     * `end` (excluded).\n     *\n     * Requirements:\n     * - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`\n     */\n    function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {\n        (bool success, address value) = tryParseAddress(input, begin, end);\n        if (!success) revert StringsInvalidAddressFormat();\n        return value;\n    }\n\n    /**\n     * @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly\n     * formatted address. See {parseAddress-string} requirements.\n     */\n    function tryParseAddress(string memory input) internal pure returns (bool success, address value) {\n        return tryParseAddress(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly\n     * formatted address. See {parseAddress-string-uint256-uint256} requirements.\n     */\n    function tryParseAddress(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) internal pure returns (bool success, address value) {\n        if (end > bytes(input).length || begin > end) return (false, address(0));\n\n        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2(\"0x\"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty\n        uint256 expectedLength = 40 + hasPrefix.toUint() * 2;\n\n        // check that input is the correct length\n        if (end - begin == expectedLength) {\n            // length guarantees that this does not overflow, and value is at most type(uint160).max\n            (bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);\n            return (s, address(uint160(v)));\n        } else {\n            return (false, address(0));\n        }\n    }\n\n    function _tryParseChr(bytes1 chr) private pure returns (uint8) {\n        uint8 value = uint8(chr);\n\n        // Try to parse `chr`:\n        // - Case 1: [0-9]\n        // - Case 2: [a-f]\n        // - Case 3: [A-F]\n        // - otherwise not supported\n        unchecked {\n            if (value > 47 && value < 58) value -= 48;\n            else if (value > 96 && value < 103) value -= 87;\n            else if (value > 64 && value < 71) value -= 55;\n            else return type(uint8).max;\n        }\n\n        return value;\n    }\n\n    /**\n     * @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.\n     *\n     * WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.\n     *\n     * NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of\n     * RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode\n     * characters that are not in this range, but other tooling may provide different results.\n     */\n    function escapeJSON(string memory input) internal pure returns (string memory) {\n        bytes memory buffer = bytes(input);\n        bytes memory output = new bytes(2 * buffer.length); // worst case scenario\n        uint256 outputLength = 0;\n\n        for (uint256 i; i < buffer.length; ++i) {\n            bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));\n            if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {\n                output[outputLength++] = \"\\\\\";\n                if (char == 0x08) output[outputLength++] = \"b\";\n                else if (char == 0x09) output[outputLength++] = \"t\";\n                else if (char == 0x0a) output[outputLength++] = \"n\";\n                else if (char == 0x0c) output[outputLength++] = \"f\";\n                else if (char == 0x0d) output[outputLength++] = \"r\";\n                else if (char == 0x5c) output[outputLength++] = \"\\\\\";\n                else if (char == 0x22) {\n                    // solhint-disable-next-line quotes\n                    output[outputLength++] = '\"';\n                }\n            } else {\n                output[outputLength++] = char;\n            }\n        }\n        // write the actual length and deallocate unused memory\n        assembly (\"memory-safe\") {\n            mstore(output, outputLength)\n            mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))\n        }\n\n        return string(output);\n    }\n\n    /**\n     * @dev Reads a bytes32 from a bytes array without bounds checking.\n     *\n     * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the\n     * assembly block as such would prevent some optimizations.\n     */\n    function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {\n        // This is not memory safe in the general case, but all calls to this private function are within bounds.\n        assembly (\"memory-safe\") {\n            value := mload(add(add(buffer, 0x20), offset))\n        }\n    }\n}\n"},{"file_path":"src/interfaces/IMintRedeemController.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\n/// @notice The one-bit pause surface of a wired module, declared here because `previewRedeem` must\n///         read the reserve's pause and `IReserveManager` does not declare it.\n/// @dev CANTINA 3.1.3 LIMB (a), CLOSED BY CONSTRUCTION ON THIS INSTANCE. On Ethereum the quote read\n///      the controller pause and the token pause but not the reserve's, so it could publish a full\n///      price for a redemption whose every release is `whenNotPaused`. The disposition there was\n///      \"an integrator should read `ReserveManager.paused()` alongside the quote\", because closing\n///      it was an upgrade. The mechanical reason the sibling fix missed the third surface is that\n///      `ReserveManager` gets `paused()` from `PausableUpgradeable` and never declares it on its own\n///      interface, so nothing in the type system pointed at it. This declaration is that pointer.\ninterface IPausableModule {\n    /// @notice True while the module refuses its `whenNotPaused` entry points.\n    function paused() external view returns (bool);\n}\n\n/// @title IMintRedeemController\n/// @notice KYC-gated issuance and redemption of USDfr against canonical USDC, and the enforcement\n///         point of the protocol's solvency rule. MINT is at par and is CLOSED while the protocol\n///         is under-backed. REDEMPTION is at par while the protocol is whole; while it is short it\n///         settles at the JUNIOR-DRAWN price, which is at least the coverage ratio and MAY BE PAR,\n///         and which the caller must elect via `redeem(uint256,uint256)`.\n///         AUDIT FIX (SWEEP-2 S2-I1) — THIS FILE-LEVEL LINE SAID \"at the coverage ratio while it is\n///         short\", the THIRD round in which a false settlement claim sat on the one line an\n///         explorer or ABI doc renders first. SWEEP-1 MRC-F2 corrected the two `redeem` overloads\n///         and the contract-level block and left this headline. Falsified by the shipped\n///         `ADR0034Y_AtomicJuniorExitDraw::test_Y_theExitSettlesAtParWhileCuratorCapitalStandsIntact`\n///         and by SWEEP-2 S2-F3, in which a sub-par book settled at PAR because ADR-0034 Y-bis drew\n///         junior capital forward to fund it.\n/// @dev THE SOLVENCY RULE IS NOT ADR-0012's ABSOLUTE PREDICATE ANY MORE, AND THIS HEADLINE USED TO\n///      SAY IT WAS (corrected in audit round R18). Until R18 this contract-level notice line read \"KYC-gated 1:1\n///      mint/redeem … `USDfr.totalSupply() <= backingValue()` after every supply-affecting op\".\n///      Both halves were false of the shipped code, and an auditor handed ADR-0012 plus this\n///      interface as the specification would reasonably have reported \"the contract does not\n///      enforce its stated invariant\" as a High. What the contract actually enforces:\n///        - Redemption is NOT 1:1. R16-M3 made the exit price `backing / supply` while short, and\n///          R17 gave the one-argument form a PAR FLOOR, so it reverts rather than settling short.\n///        - The absolute predicate was REPLACED by the NON-WORSENING rule: an operation may not\n///          increase `deficit = max(0, totalSupply - backingValue)`. While the protocol is whole\n///          that reduces exactly to ADR-0012 and still reverts with\n///          `Controller_BackingInvariantViolated`; while it is short it permits the operations that\n///          repair holders' position and refuses the ones that dilute it. See\n///          `MintRedeemController`'s contract-level NatSpec, which sets out the whole model.\n///        - It is not asserted \"after every supply-affecting op\": `burnLoss` carries NO solvency\n///          assertion, deliberately (finding M6 — the assertion it used to carry was unfalsifiable).\n///      The comment was not independently wrong: it correctly quoted `ADR/0012-backing-invariant.md`\n///      (Status: Accepted), which still states the superseded absolute rule verbatim as \"a hard\n///      on-chain check on every supply-affecting operation\". THAT ADR MUST BE AMENDED OR SUPERSEDED\n///      so the code and the decision record agree; it is OUTSTANDING and is Forest Road's to take\n///      (CLAUDE.md §0.7).\ninterface IMintRedeemController {\n    // ── Events ───────────────────────────────────────────────────────────\n    event Minted(address indexed user, uint256 usdcIn, uint256 usdfrOut);\n    event Redeemed(address indexed user, uint256 usdfrIn, uint256 usdcOut);\n    /// @notice Emitted when USDfr is minted against attested yield receipts (waterfall path).\n    event YieldMinted(address indexed to, uint256 amount);\n    /// @notice Emitted when USDfr is burned to realize a loss (cascade layer 3).\n    event LossBurned(address indexed from, uint256 amount);\n    /// @notice AUDIT FIX (R16-M3). Emitted IN ADDITION to `Redeemed` when a redemption settled\n    ///         below par because the protocol was under-backed. Carries the supply and backing\n    ///         the quote was struck against, so the coverage ratio applied to any exit is\n    ///         reconstructable purely from events (CLAUDE.md §3.1).\n    /// @param user The redeemer.\n    /// @param usdfrBurned USDfr burned (whole-USDC-unit aligned).\n    /// @param usdcOut Native USDC units actually paid out.\n    /// @param supply `totalUSDfr()` before the redemption.\n    /// @param backing `backingValue()` before the redemption.\n    event SubParRedemption(address indexed user, uint256 usdfrBurned, uint256 usdcOut, uint256 supply, uint256 backing);\n    /// @notice AUDIT FIX (R17). Emitted alongside `SubParRedemption`. Records the value\n    ///         PERMANENTLY crystallised out of the senior layer by an exit priced against a\n    ///         REVERSIBLE impairment mark, and the running total. `mintableHeadroom()` nets the\n    ///         running total out, so value recovered when the mark is released stays in the pool\n    ///         as coverage instead of being minted to the `sUSDfr` vault as yield.\n    /// @param user The redeemer who bore it.\n    /// @param amount `usdfrBurned - usdcOut * 1e12` for this exit, in 18-decimal USD.\n    /// @param cumulative `seniorSubParShortfall()` after this exit.\n    event SeniorShortfallCrystallised(address indexed user, uint256 amount, uint256 cumulative);\n    /// @notice AUDIT FIX (R16-M1). Governance authorized or revoked a `mintYield` destination.\n    event YieldSinkUpdated(address indexed account, bool authorized);\n    /// @notice AUDIT FIX (R16-M1/M2). Governance authorized or revoked a `burnLoss` source.\n    event LossSourceUpdated(address indexed account, bool authorized);\n\n    // ── Errors ───────────────────────────────────────────────────────────\n    error Controller_NotKYCAllowed(address account);\n    error Controller_BackingInvariantViolated(uint256 supply, uint256 backing);\n    error Controller_ZeroAmount();\n    error Controller_AmountTooSmall(uint256 usdfrAmount);\n\n    /// @notice An unratified arm refused a direct redemption.\n    /// @param armId Active custody arm.\n    /// @param usdcOut Proposed settlement in native USDC units.\n    /// @param usdfrIn USDfr claims proposed for redemption.\n    error Controller_ReserveLossArmFreeze(uint256 armId, uint256 usdcOut, uint256 usdfrIn);\n\n    /// @notice The redemption would have burned more USDfr than the post-draw supply.\n    /// @dev CANTINA 3.1.1, RE-DERIVED AT SCALE 1 AND CLOSED RATHER THAN ACKNOWLEDGED. On Ethereum\n    ///      the whole-unit grid returned `M mod 1e12` wei of headroom at the top of the range, so\n    ///      `usdfrIn + drawn` overflowed only for inputs within 1e12 of `type(uint256).max` - a\n    ///      panic window of width at most 2**40, which is why \"acknowledged\" was a defensible\n    ///      judgement. At scale 1 the grid is the identity, `usdfrIn == usdfrAmount` exactly, and\n    ///      the window widens to the whole top `drawn` of the range. That is not the same judgement\n    ///      about the same object. Bounding the SUM rather than the addend makes the overflow\n    ///      UNREPRESENTABLE rather than merely unlikely, refuses only inputs no holder can hold, and\n    ///      makes `previewRedeem` answer a controller error instead of `Panic(0x11)`.\n    /// @param usdfrIn The amount the exit would burn.\n    /// @param bound `supply - drawn`, which `supply - drawn <= supply` makes underflow-free because\n    ///        `drawn` was burned out of `supply`.\n    error Controller_RedeemExceedsSupply(uint256 usdfrIn, uint256 bound);\n    /// @notice AUDIT FIX (R4-01): the user par paths are closed while the reserve holds less USDC\n    ///         than its idle ledger claims. Recognition of the gap is permissionless and immediate;\n    ///         restoring custody, or the authenticated custody-loss cascade writing the ledger down\n    ///         to the live balance, reopens mint and redeem with no governance action.\n    /// @param shortfallValue The observable custody gap in 18-decimal USD.\n    /// @param recognizedBacking Backing net of that gap — the honest basis.\n    error Controller_ReserveCustodyShortfall(uint256 shortfallValue, uint256 recognizedBacking);\n\n    /// @notice AUDIT FIX (R16-M3/M4/M5). The operation would have WIDENED an already-standing\n    ///         backing deficit. Distinct from `Controller_BackingInvariantViolated`, which is\n    ///         raised when a whole protocol would be pushed below par: an integrator seeing that\n    ///         error inside a knowingly sub-par protocol would reasonably read it as the standing\n    ///         condition rather than as a refusal of this specific call.\n    /// @param deficitBefore `max(0, totalUSDfr() - backingValue())` before the operation.\n    /// @param deficitAfter The same quantity after it, which must not exceed `deficitBefore`.\n    error Controller_DeficitWorsened(uint256 deficitBefore, uint256 deficitAfter);\n\n    /// @notice A paired-yield baseline is already open, so a second cannot be started.\n    error Controller_PairedYieldAlreadyOpen(address caller);\n    /// @notice A split mint must consume this caller's existing paired backing baseline.\n    error Controller_PairedYieldRequired();\n    /// @notice A paired operation cannot complete against a changed retention obligation.\n    error Controller_PairedRetentionChanged(uint256 beforeRequirement, uint256 afterRequirement);\n    /// @notice The protocol fee cannot exceed the total amount being issued.\n    error Controller_InvalidYieldSplit(uint256 total, uint256 fee);\n\n    /// @notice A paired-yield baseline was recorded before its caller moved backing.\n    event PairedYieldOpened(address indexed caller, uint256 supplyBefore, uint256 backingBefore);\n\n    /// @notice A stranded paired-yield baseline was cleared by governance.\n    event PairedYieldCleared(address indexed caller);\n\n    /// @notice Records the supply/backing baseline for a yield mint whose backing leg moves first.\n    function beginPairedYield() external;\n\n    /// @notice Governance escape for a paired-yield baseline stranded by a reverted operation.\n    function clearStalePairedYield() external;\n\n    /// @notice AUDIT FIX (R16-M3). Par issuance is closed while the protocol is under-backed for\n    ///         ANY reason — a G3 conservative mark or a residual cascade deficit as well as the\n    ///         R4-01 custody gap. `redeem` deliberately stays OPEN in this state and re-prices to\n    ///         the coverage ratio; see `previewRedeem`.\n    /// @param supply `totalUSDfr()` at the time of refusal.\n    /// @param backing `backingValue()` at the time of refusal.\n    error Controller_MintClosedWhileUnderBacked(uint256 supply, uint256 backing);\n\n    /// @notice AUDIT FIX (R16-L2). The USDC the user was charged did not arrive in the reserve's\n    ///         custody, or the reserve credited a value that does not match it. Measured from the\n    ///         reserve's own token balance rather than from anything the reserve reports about\n    ///         itself, so `mint` no longer derives both sides of its safety check from one module.\n    /// @param requested Native USDC units pulled from the user.\n    /// @param delivered The reserve's measured USDC balance increase.\n    /// @param credited The 18-decimal value `depositUSDC` reported.\n    error Controller_DepositNotCustodied(uint256 requested, uint256 delivered, uint256 credited);\n\n    /// @notice AUDIT FIX (R16-M1). `to` is not a governance-authorized yield destination.\n    error Controller_NotYieldSink(address to);\n\n    /// @notice AUDIT FIX (R16-M1/M2). `from` is not a governance-authorized loss source. Without\n    ///         this, `burnLoss` and `mintYield` composed into arbitrary confiscation, and\n    ///         `USDfr.burn`'s allowance-free burn made any holder seizable one-sidedly.\n    error Controller_NotLossSource(address from);\n\n    /// @notice AUDIT FIX (R17). A loss source must be a CONTRACT. `burnLoss` burns with no\n    ///         allowance, carries no backing assertion and is deliberately not pausable, so\n    ///         listing an EOA would restore finding M2 — a forced, non-pro-rata seizure of one\n    ///         named holder — in a single routine-looking timelock transaction. Mirrors\n    ///         `ReserveManager.setLossAbsorber`/`setLossController`. Deliberately NOT applied to\n    ///         `setYieldSink`, whose fee-recipient treasury may legitimately be an EOA.\n    error Controller_LossSourceNotContract(address account);\n\n    /// @notice AUDIT FIX (R17). The settled price was below the floor the caller named. The\n    ///         one-argument `redeem` supplies the PAR floor, so it reverts with this rather than\n    ///         silently haircutting a holder against a mark that may later be released.\n    /// @param usdcOut What the redemption would have paid.\n    /// @param minUsdcOut The floor the caller required.\n    error Controller_SlippageExceeded(uint256 usdcOut, uint256 minUsdcOut);\n\n    /// @notice AUDIT FIX (R17). Backing has fallen to zero, so there is nothing to pay out at any\n    ///         size. Previously this answered `Controller_AmountTooSmall`, which told the holder\n    ///         their amount was the problem when the truth was that the protocol was worth nothing.\n    /// @param supply `totalUSDfr()` at the time of refusal.\n    error Controller_NoRedeemableBacking(uint256 supply);\n\n    /// @notice AUDIT FIX (R17). The USDC the redemption was priced at did not reach the redeemer.\n    ///         The outflow twin of `Controller_DepositNotCustodied`: R16-L2 installed an\n    ///         independent measurement on the inflow leg only, leaving `redeem` to take the\n    ///         reserve's own word for a release on the leg where the holder's USDfr is already\n    ///         burned and the loss is irreversible.\n    /// @param expected The quoted payout in native USDC units.\n    /// @param settled The redeemer's measured USDC balance increase.\n    /// @param usdfrBurned The USDfr burned to pay for it.\n    error Controller_RedemptionNotSettled(uint256 expected, uint256 settled, uint256 usdfrBurned);\n\n    /// @notice AUDIT FIX (R17). USDC was left sitting on the controller after a mint. The\n    ///         controller is value-neutral at rest; a reserve that funded the deposit from\n    ///         somewhere other than the controller's allowance satisfies the delivery equality\n    ///         while leaving the user's cash here with a live approval against it.\n    /// @dev Measured as a DELTA across the call, never as an absolute balance: anyone can send\n    ///      USDC to the controller, so `balanceOf(this) != 0` would be a one-wei permanent\n    ///      griefing lock on `mint`.\n    /// @param balanceBefore The controller's USDC balance before the deposit leg.\n    /// @param balanceAfter Its balance after it. Any inequality is refused.\n    error Controller_CashStrandedOnController(uint256 balanceBefore, uint256 balanceAfter);\n\n    /// @notice AUDIT FIX (R17). The operation would have widened the deficit measured on the\n    ///         RECOGNITION-AWARE basis — backing net of the custody shortfall the reserve can\n    ///         observe right now. Raised only by `mintYield`, the one supply-EXPANDING path with\n    ///         no custody precondition; `mint` and `redeem` are refused earlier by\n    ///         `Controller_ReserveCustodyShortfall`, and `burnLoss` is deliberately ungated.\n    /// @param deficitBefore `max(0, totalUSDfr() - recognizedBackingValue())` before the call.\n    /// @param deficitAfter The same quantity after it.\n    error Controller_RecognizedDeficitWorsened(uint256 deficitBefore, uint256 deficitAfter);\n\n    /// @notice AUDIT FIX (R17). A yield mint would have consumed value retained against\n    ///         `seniorSubParShortfall()` — the haircut crystallised out of holders who exited\n    ///         against a REVERSIBLE impairment mark. `mintableHeadroom()` advertises the retention;\n    ///         this error enforces it.\n    /// @dev CORRECTED (SWEEP-1 MRC-F3, 2026-08-08). This sentence used to end \"...because\n    ///      `WaterfallEngine.fund`'s origination-fee mint is not sized off that headroom and would\n    ///      otherwise spend it.\" THAT JUSTIFICATION EXPIRED AT R18. `WaterfallEngine.fund` now\n    ///      reads `uint256 headroom = $.controller.mintableHeadroom();` and clamps\n    ///      `mintable = fee <= headroom ? fee : headroom` (WaterfallEngine.sol:195-197);\n    ///      `MintRedeemController` says so in two places, and\n    ///      `test_R18_A1_originationSurvivesACrystallisedHaircut` passes over the clamped path.\n    ///      This is the same class of defect the merge author fixed on\n    ///      `CollateralRegistry.conservativeSeniorMark`: a stale justification on a value path is\n    ///      a defect, because the next engineer prunes the guard once they discover the reason\n    ///      given for it is untrue.\n    ///\n    ///      THE ERROR IS STILL LOAD-BEARING, ON A DIFFERENT GROUND — DO NOT DELETE IT. It is the\n    ///      LAST line of defence rather than the only one. `CREDIT_ROLE` gates `mintYield`, and\n    ///      `Deploy.s.sol` grants that role to `WaterfallEngine` alone TODAY; a second grantee, or\n    ///      any future unclamped call site, would spend the junior retention silently. The clamp is\n    ///      a caller-side property; this is the callee-side one.\n    /// @param threshold THE BOUND THAT WAS ACTUALLY ENFORCED, which differs by branch and is why\n    ///        this parameter is not named `retention`. On an ordinary yield mint it is\n    ///        `seniorSubParShortfall()`, the junior retention the surplus must not fall below. On a\n    ///        PAIRED mint opened by `beginPairedYield` it is the surplus recorded BEFORE the caller\n    ///        moved any backing, because a paired move raises backing and supply by the identical\n    ///        amount and the property enforced there is exact neutrality rather than a floor.\n    ///        Reporting the retention on the paired branch made the error describe a rule that\n    ///        branch does not apply; corrected 2026-09-10.\n    /// @param surplus `max(0, recognizedBackingValue() - totalUSDfr())` after the mint.\n    error Controller_SeniorRetentionBreached(uint256 threshold, uint256 surplus);\n\n    /// @notice AUDIT FIX (R18). The reserve took the USDC and reported the right credit but did not\n    ///         BOOK it as backing. The recognition twin of `Controller_DepositNotCustodied`: R16-L2\n    ///         measured custody and R17 measured the reported credit, while recognition was left to\n    ///         the NON-WORSENING deficit rule — which a standing surplus silently pays for, up to\n    ///         its own size. Measured as a DELTA on `backingValue()` across the deposit leg, so no\n    ///         surplus can absorb it, and as an EQUALITY, so an over-booking reserve is refused too.\n    /// @param credited The 18-decimal value `depositUSDC` reported.\n    /// @param recognized The measured increase in `backingValue()` across the same call.\n    error Controller_DepositNotRecognized(uint256 credited, uint256 recognized);\n\n    /// @notice AUDIT FIX (R18). A loss source must not be an EIP-7702 DELEGATED EOA. Since Pectra\n    ///         an ordinary key-controlled wallet that signed a delegation carries a 23-byte\n    ///         `0xef0100`-prefixed code field, so `EXTCODESIZE` returns 23 and\n    ///         `Controller_LossSourceNotContract`'s check admitted it — leaving finding M2 (a\n    ///         forced, allowance-free, non-pro-rata seizure of one named holder, unstoppable by the\n    ///         guardian) one routine-looking timelock transaction away for exactly the class of\n    ///         wallet the guard claimed to exclude.\n    error Controller_LossSourceIsDelegatedEOA(address account);\n\n    /// @notice AUDIT FIX (R18). A composite view was read while this contract's reentrancy guard\n    ///         was entered — i.e. from inside a supply change that has not finished settling — and\n    ///         would have answered a number known to be false.\n    /// @dev `_redeem` burns before it releases, and `DefaultManager.realizeLoss` burns before it\n    ///      writes backing down; `USDfr._update` fires the participation-points hook inside every\n    ///      one of those burns. From there `mintableHeadroom()` read the entire realised loss of a\n    ///      cascade as distributable yield capacity, `backingInvariantHolds()` read TRUE on a short\n    ///      book and `previewRedeem` quoted PAR on it. Reverting is the honest answer and is\n    ///      fail-closed for an integrator; returning the number is the R4-01 self-contradiction one\n    ///      frame deeper. The raw delegating views (`backingValue`, `recognizedBackingValue`,\n    ///      `totalUSDfr`) are NOT gated: each is true whenever it is read. Only the composites are.\n    error Controller_ViewUnavailableMidTransition();\n\n    /// @notice `redeem(uint256,uint256,uint256)` was included after the caller's deadline\n    ///         (ADR-0034 W).\n    error Controller_DeadlinePassed(uint256 deadline, uint256 nowTimestamp);\n    /// @notice The junior-draw source named by `ReserveManager.lossAbsorber()` is not on the\n    ///         governance-maintained `setLossSource` list (ADR-0034 Y-bis). Fail-closed: the exit\n    ///         refuses rather than burning a third party's USDfr on an unvouched-for pointer.\n    error Controller_ExitDrawSourceNotAuthorised(address source);\n    /// @notice The junior-draw source reported one number and moved another, or delivered more\n    ///         than was asked of it (ADR-0034 Y-bis). Measured, not trusted.\n    error Controller_ExitDrawNotDelivered(uint256 requested, uint256 reported, uint256 measured);\n\n    /// @notice Junior capital was drawn forward, in cascade order, to fund this exit's price\n    ///         (ADR-0034 Y-bis). `drawn` USDfr was burned out of the junior layers.\n    event SeniorExitJuniorDrawn(address indexed redeemer, uint256 required, uint256 drawn);\n\n    // ── User paths (KYC-gated) ───────────────────────────────────────────\n    /// @notice Deposits USDC (6 decimals) and mints USDfr 1:1 in 18-decimal USD units.\n    function mint(uint256 usdcAmount) external returns (uint256 usdfrOut);\n\n    /// @notice Burns USDfr and releases the reserve's cash equivalent AT PAR. While the protocol\n    ///         is short this form settles at par out of JUNIOR capital drawn forward in the same\n    ///         transaction (ADR-0034 Y-bis), and reverts `Controller_SlippageExceeded` only once\n    ///         that draw cannot reach par. It never haircuts the caller. Use\n    ///         `redeem(uint256,uint256)` to elect a sub-par exit.\n    /// @dev AUDIT FIX (R18) CORRECTED THE NOTICE LINE ABOVE, which every block explorer, ABI\n    ///      doc and integrator reads first. It said this form is \"priced at the coverage ratio: par\n    ///      while the protocol is whole, `backing / supply` while it is short\". After R17's par\n    ///      floor that is false of THIS form. The coverage-ratio behaviour described below is\n    ///      R16-M3's and is true of the two-argument form.\n    /// @dev CORRECTED AGAIN (SWEEP-1 MRC-F2, 2026-08-08) — SAME LINE, ONE ROUND LATER. R18's\n    ///      replacement said this form \"REVERTS\" while short, full stop. That stopped being true\n    ///      at ADR-0034 Y-bis, which draws curator first-loss and the sGROVE backstop forward in\n    ///      the same transaction to fund the cascade-ordered price. MEASURED: with a gross quote of\n    ///      185,928.705440 USDC this form settled 200,000.000000 — AT PAR, out of junior capital.\n    ///      It reverts only when the draw cannot reach par. Two successive rounds put a false\n    ///      settlement claim on the one line integrators read first; check it against\n    ///      `MintRedeemController._quoteRedeem` and `_drawJuniorForExit` before editing it again.\n    /// @dev AUDIT FIX (R17): THIS FORM SUPPLIES THE PAR FLOOR. It settles at par or reverts with\n    ///      `Controller_SlippageExceeded`. R16 made the price a live function of state and left\n    ///      this one-argument signature accepting whatever the ratio was at inclusion, while\n    ///      several NON-timelocked paths move backing down in the same block. Taking a haircut is\n    ///      now an explicit election: quote with `previewRedeem`, then call the two-argument form\n    ///      with the floor you will accept.\n    function redeem(uint256 usdfrAmount) external returns (uint256 usdcOut);\n\n    /// @notice Burns USDfr and releases the reserve's cash equivalent, refusing to settle below\n    ///         `minUsdcOut`. This is the form that accepts a SUB-PAR exit — an explicit, informed\n    ///         election by the holder (R16-M3, R17).\n    /// @dev CORRECTED (SWEEP-1 MRC-F2, 2026-08-08). This line said the form \"pays the COVERAGE\n    ///      RATIO\". It pays the JUNIOR-DRAWN price, which is >= the coverage ratio and may be par:\n    ///      ADR-0034 Y-bis draws curator first-loss and the sGROVE backstop forward in the same\n    ///      transaction, and the gross `backing / supply` mark is only the floor the price degrades\n    ///      to once junior capital is exhausted. Quote with `previewRedeem`, which shares the\n    ///      drawn arithmetic.\n    /// @dev AUDIT FIX (R17). `previewRedeem` is advisory ACROSS TRANSACTIONS — it shares\n    ///      `redeem`'s arithmetic, not its state — so this parameter is the only thing that binds\n    ///      the settlement price. Pass the value `previewRedeem` returned (or lower, to tolerate\n    ///      movement).\n    /// @dev THE DEADLINE IS NOW SHIPPED, ON A NEW SIGNATURE (ADR-0034 W). R17 wrote here that\n    ///      \"there is no deadline parameter: there is no AMM-style path here, and the floor alone\n    ///      is sufficient to make the exit refusable\", which argued an ACCEPTED requirement away.\n    ///      `redeem(uint256,uint256,uint256)` carries it. THIS form is deliberately left\n    ///      deadline-free rather than being given a new expiry semantic under an unchanged\n    ///      signature — see that overload's NatSpec. Prefer the three-argument form.\n    /// @param usdfrAmount USDfr offered; the burn is snapped down to the whole-USDC-unit grid.\n    /// @param minUsdcOut The lowest native-USDC payout the caller will accept. Zero accepts ANY\n    ///        price, including a deep haircut — pass zero only deliberately.\n    function redeem(uint256 usdfrAmount, uint256 minUsdcOut) external returns (uint256 usdcOut);\n\n    /// @notice Burns USDfr and releases the reserve's cash equivalent, refusing to settle below\n    ///         `minUsdcOut` or after `deadline`. THE CANONICAL EXIT (ADR-0034 W).\n    /// @dev A minimum-out bounds the PRICE; it does not bound WHEN the exit executes. Every path\n    ///      that moves the coverage ratio down is un-timelocked and publicly visible before it\n    ///      lands, so a transaction left in the mempool is a free option for whoever chooses\n    ///      inclusion. See the implementation NatSpec.\n    /// @param usdfrAmount USDfr offered; the burn is snapped down to the whole-USDC-unit grid.\n    /// @param minUsdcOut The lowest native-USDC payout the caller will accept.\n    /// @param deadline Latest `block.timestamp` at which this exit may settle.\n    function redeem(uint256 usdfrAmount, uint256 minUsdcOut, uint256 deadline) external returns (uint256 usdcOut);\n\n    // ── Protocol paths (credit layer; wired in Phases E/G) ───────────────\n    /// @notice Mints USDfr to `to` against newly received, attested backing (loan\n    ///         interest / reserve yield). `CREDIT_ROLE`.\n    /// @dev AUDIT FIX (R16-M1): `to` must be a governance-authorized yield sink. Refuses while\n    ///      the protocol is under-backed (incoming cash repairs the hole before it is paid out\n    ///      as yield) and while the controller is paused (a pause must never permit supply\n    ///      expansion). Callers should size the mint with `mintableHeadroom()`.\n    /// @dev AUDIT FIX (R17/R18): it ALSO refuses while the surplus is below\n    ///      `seniorSubParShortfall()` (`Controller_SeniorRetentionBreached`) — an ABSOLUTE level\n    ///      check that bites in states the protocol publishes as fully backed. EVERY CALLER MUST\n    ///      SIZE ITSELF OFF `mintableHeadroom()`: it is the one view that nets the retention, both\n    ///      pauses and the recognition basis. `WaterfallEngine` now does so on BOTH of its mints\n    ///      (interest since R16-M5, the origination fee since R18); a caller that does not will\n    ///      revert rather than withhold.\n    function mintYield(address to, uint256 amount) external;\n\n    /// @notice Issues one paired increase to two authorized sinks, checking the complete total.\n    /// @param senior Destination of total minus fee; unused when that amount is zero.\n    /// @param total Total new supply, justified by the backing increase since beginPairedYield.\n    /// @param feeRecipient Destination of fee; unused when fee is zero.\n    /// @param fee Part of total allocated before the senior leg, in normalized USDfr units.\n    function mintYieldSplit(address senior, uint256 total, address feeRecipient, uint256 fee) external;\n\n    /// @notice Burns USDfr from `from` to realize a loss through the cascade.\n    ///         `LOSS_BURNER_ROLE` — deliberately NOT `CREDIT_ROLE`.\n    /// @dev AUDIT FIX (R16-M1/M2): `from` must be a governance-authorized loss source, and the\n    ///      role is split from `CREDIT_ROLE` so `WaterfallEngine`, which never burns, no longer\n    ///      holds the power to. Never pausable: loss absorption must stay available.\n    function burnLoss(address from, uint256 amount) external;\n\n    // ── Governance: credit-layer endpoints (AUDIT FIX R16-M1) ────────────\n    /// @notice Authorizes (or revokes) an address as a destination for `mintYield`.\n    function setYieldSink(address account, bool authorized) external;\n\n    /// @notice Authorizes (or revokes) an address as a source for `burnLoss`.\n    function setLossSource(address account, bool authorized) external;\n\n    // ── Views ────────────────────────────────────────────────────────────\n    /// @notice Current backing value on the RECORDED-LEDGER basis\n    ///         (delegates to `ReserveManager.totalBackingValue()`).\n    /// @dev AUDIT FIX (R4-01): this is the basis the C-01 custody-loss arithmetic reconciles\n    ///      against within a single transaction and is deliberately NOT recognition-aware. For any\n    ///      solvency or exit-pricing question use `recognizedBackingValue()`.\n    function backingValue() external view returns (uint256);\n\n    /// @notice AUDIT FIX (R4-01). Backing net of the custody shortfall the reserve can observe\n    ///         right now (delegates to `ReserveManager.recognizedBackingValue()`).\n    function recognizedBackingValue() external view returns (uint256);\n\n    /// @notice Current USDfr total supply.\n    function totalUSDfr() external view returns (uint256);\n\n    /// @notice True if supply is covered on the RECORDED ledger.\n    /// @dev Compatibility diagnostic only. DELIBERATELY BLIND TO THE CUSTODY SHORTFALL and no\n    ///      longer consumed by `WaterfallEngine.distribute`: that path enforces exact receipt and\n    ///      a non-worsening recognised deficit. Do not use this absolute view as an admission\n    ///      gate, user-path condition, exit price, or solvency display.\n    function creditServicingBackingHolds() external view returns (bool);\n\n    /// @notice True if the backing invariant currently holds. Public so anyone can check.\n    /// @dev AUDIT FIX (R4-01): measured against `recognizedBackingValue()`, so it can no longer\n    ///      report true in the same block in which `observeIdleUSDC()` publishes a shortfall.\n    /// @dev AUDIT FIX (R18): reverts with `Controller_ViewUnavailableMidTransition` if called from\n    ///      inside an unsettled supply change — mid-burn it read TRUE on a 20%-short book.\n    function backingInvariantHolds() external view returns (bool);\n\n    /// @notice AUDIT FIX (R16-M4/M5). `max(0, totalUSDfr() - backingValue())` on the RECORDED\n    ///         basis — the quantity every supply-affecting path refuses to increase.\n    /// @dev AUDIT FIX (R18): reverts with `Controller_ViewUnavailableMidTransition` if called from\n    ///      inside an unsettled supply change; it composes a supply reading with a backing reading.\n    function backingDeficit() external view returns (uint256);\n\n    /// @notice AUDIT FIX (R16-M4). The same quantity on the RECOGNITION-AWARE basis (net of any\n    ///         observable custody shortfall).\n    /// @dev This is what `WaterfallEngine.distribute` gates on, comparing it before and after the\n    ///      call. Non-worsening rather than absolute, so a repayment that REPAIRS backing is not\n    ///      refused merely because the protocol was already short — which is what previously\n    ///      turned a single conservative mark into a total halt of repayment processing.\n    /// @dev AUDIT FIX (R18): reverts with `Controller_ViewUnavailableMidTransition` if called from\n    ///      inside an unsettled supply change, as `backingDeficit()` does.\n    function recognizedDeficit() external view returns (uint256);\n\n    /// @notice AUDIT FIX (R16-M5, corrected by R17, R18 and SWEEP-2 S2-F4). How much NEW supply may\n    ///         be minted without widening the deficit or paying away value the protocol owes:\n    ///         `(paused() || USDfr.paused()) ? 0 : max(0, recognizedBackingValue() - totalUSDfr() -\n    ///         seniorSubParShortfall() - ReserveManager.exitPrepaidAbsorption())`.\n    /// @dev AUDIT FIX (SWEEP-2 S2-F4) — THE FOURTH TERM WAS MISSING FROM THIS PUBLISHED FORMULA, AND\n    ///      THE STRING `exitPrepaid` APPEARED NOWHERE IN THIS FILE. ADR-0034 Y-bis added\n    ///      `ReserveManager.exitPrepaidAbsorption()` to the implementation and not to the\n    ///      specification. This is the one view that decides how much yield may be minted, and\n    ///      `mintYield`'s note below warns that \"a caller that does not size itself off\n    ///      `mintableHeadroom()` will revert rather than withhold\" — so a caller sizing off the\n    ///      PUBLISHED formula got `Controller_SeniorRetentionBreached` /\n    ///      `Controller_RecognizedDeficitWorsened` instead of a withholding. MEASURED: published\n    ///      formula 9,900.99e18, code 0, undocumented term 9,900.99e18. The retention has NO\n    ///      RESTITUTION PATH and is not necessarily released — see `mintableHeadroom`'s own\n    ///      implementation note and the SWEEP-2 S2-F3 register entry.\n    /// @dev AUDIT FIX (R18): the pause term reads BOTH pauses. R17 read only the controller's, while\n    ///      the same guardian key holds `GUARDIAN_ROLE` on `USDfr` and a token pause refuses every\n    ///      mint — so one transaction still reverted every interest-bearing\n    ///      `WaterfallEngine.distribute` in full. `WaterfallEngine.fund` now sizes its origination\n    ///      fee off this view as well, so under either pause it withholds the fee instead of\n    ///      reverting the origination.\n    /// @dev AUDIT FIX (R18): reverts with `Controller_ViewUnavailableMidTransition` if called from\n    ///      inside an unsettled supply change — mid-cascade it read the entire realised loss as\n    ///      distributable yield capacity.\n    /// @dev `WaterfallEngine._routeInterest` reads this and distributes only what fits,\n    ///      WITHHOLDING the rest so the cash stays in the reserve and repairs backing. That is\n    ///      the protocol-native cure for a residual deficit: loan interest closes the hole\n    ///      automatically, with no governance action and no recapitalisation, and yield resumes\n    ///      by itself once it is closed.\n    /// @dev AUDIT FIX (R17): the basis is RECOGNITION-AWARE. Measured on the recorded ledger the\n    ///      cure was blind to the entire deficit class R4-01 exists to recognise — a custody hole\n    ///      left headroom equal to the whole interest receipt, so the clamp withheld nothing, the\n    ///      protocol fee was taken on the gross, and the hole never closed while every user was\n    ///      frozen out of `mint` and `redeem`. It is also zero while the controller is PAUSED, so\n    ///      the pause withholds yield instead of reverting every borrower repayment, and it nets\n    ///      out `seniorSubParShortfall()`.\n    function mintableHeadroom() external view returns (uint256);\n\n    /// @notice AUDIT FIX (R17). Cumulative value crystallised out of the senior layer by sub-par\n    ///         exits, in 18-decimal USD. Monotonically non-decreasing; no setter.\n    /// @dev Sub-par exits are priced against `recognizePrincipalImpairment` marks, which are\n    ///      REVERSIBLE by design (`releasePrincipalImpairment`). The exiter's loss is not. Without\n    ///      this, value recovered when a mark is released reappeared as `mintableHeadroom()` and\n    ///      was minted to the `sUSDfr` vault — the senior's haircut becoming the yield layer's\n    ///      income, ahead of the §1.3 cascade's first two layers. Netting it out of the headroom\n    ///      keeps recovered value in the pool as coverage instead. Reconstructable from\n    ///      `SeniorShortfallCrystallised` events.\n    /// @dev AUDIT FIX (R18) — WHAT IT COSTS, CORRECTED. `mintYield` enforces this as an ABSOLUTE\n    ///      level check, so it withholds ORIGINATION FEES as well as interest, and it does so in\n    ///      states the protocol publishes as fully backed and even OVER-backed. Under R17 that\n    ///      REFUSED `WaterfallEngine.fund` outright and therefore blocked the only cure the\n    ///      mechanism names (interest requires a facility; a facility requires `fund`) — finding M5\n    ///      on the origination axis. `fund` now clamps its fee to `mintableHeadroom()` and withholds\n    ///      instead. The retention is unchanged. Read `MintRedeemController.seniorSubParShortfall`\n    ///      for the full statement, including the known over-charge on a REALISED (as opposed to\n    ///      released) loss, which is outstanding.\n    function seniorSubParShortfall() external view returns (uint256);\n\n    /// @notice AUDIT FIX (R16-M3/L3). Quotes a redemption without executing it: the USDC that\n    ///         would be paid and the USDfr that would actually be burned.\n    /// @dev Returns `(0, 0)` — BOTH components — in FOUR cases: the amount is below the settleable\n    ///      floor; the protocol has no backing; the protocol is empty (`totalUSDfr() == 0`); or\n    ///      REDEMPTION IS CLOSED because the reserve has an unreconciled custody shortfall\n    ///      (`idleCustodyShortfall() != 0`, AUDIT FIX R18). In all four, nothing is payable at any\n    ///      size, which is what `(0, 0)` has always meant here. A frontend can therefore state the\n    ///      floor, or state that redemption is unavailable, without simulating a revert.\n    /// @dev AUDIT FIX (R18) added the fourth case. R17 changed WHICH number this published over a\n    ///      custody hole; it did not change WHETHER one was published, so in the standing R4-01\n    ///      state — where `backingInvariantHolds()` already publishes FALSE — this returned a full,\n    ///      settleable-looking quote for a call that `_requireCustodiedReserve` then refuses with\n    ///      `Controller_ReserveCustodyShortfall`. Passing that number back in as `minUsdcOut`, as\n    ///      the sentence above directs, reverted.\n    /// @dev AUDIT FIX (R18): reverts with `Controller_ViewUnavailableMidTransition` if called from\n    ///      inside an unsettled supply change (the participation-points hook fires mid-burn, where\n    ///      this view quoted PAR on a short book).\n    /// @dev AUDIT FIX (R17), correcting R16's claim that \"quote and settlement cannot diverge\".\n    ///      This view shares `redeem`'s ARITHMETIC; it does not share `redeem`'s preconditions and\n    ///      it does not bind the price. Two consequences a caller must know:\n    ///        - It is priced on `recognizedBackingValue()`, because unlike `redeem` it is not\n    ///          behind `_requireCustodiedReserve`. On the recorded basis it published a par quote\n    ///          in exactly the state where the recorded ledger is known to be false and the call it\n    ///          quoted for would revert. Wherever `redeem` is reachable the two bases are equal, so\n    ///          the quote is exact there.\n    ///        - It is a snapshot of the current state, valid for that state only. Pass it back into\n    ///          `redeem(usdfrAmount, minUsdcOut)`; that parameter, not this view, is what binds.\n    function previewRedeem(uint256 usdfrAmount) external view returns (uint256 usdcOut, uint256 usdfrIn);\n\n    /// @notice AUDIT FIX (R16-M1). True if `account` may receive `mintYield`.\n    function isYieldSink(address account) external view returns (bool);\n\n    /// @notice AUDIT FIX (R16-M1/M2). True if `account` may be burned from by `burnLoss`.\n    function isLossSource(address account) external view returns (bool);\n\n    /// @notice Wired module addresses, used to bind ReserveManager's independent loss check to\n    ///         the controller that actually points back to that reserve.\n    function modules() external view returns (address usdfr, address compliance, address reserves);\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity >=0.5.0;\n\n/**\n * @title ERC-721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC-721 asset contracts.\n */\ninterface IERC721Receiver {\n    /**\n     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n     * by `operator` from `from`, this function is called.\n     *\n     * It must return its Solidity selector to confirm the token transfer.\n     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be\n     * reverted.\n     *\n     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n     */\n    function onERC721Received(\n        address operator,\n        address from,\n        uint256 tokenId,\n        bytes calldata data\n    ) external returns (bytes4);\n}\n"},{"file_path":"src/libraries/BridgeAccrualLib.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {IContinuousAccrual, IAccrualToken} from \"../interfaces/IContinuousAccrual.sol\";\nimport {IMintRedeemController} from \"../interfaces/IMintRedeemController.sol\";\nimport {IReserveManager} from \"../interfaces/IReserveManager.sol\";\n\ninterface IMixedInterestVersion {\n    function mixedInterestVersion() external pure returns (bytes32);\n}\n\ninterface IMixedInterestReserve {\n    function enableMixedInterest() external;\n}\n\n/// @title BridgeAccrualLib\n/// @notice Fixed-ABI validation of the bridge's permanent continuous-accounting source.\n/// @dev Linked calls execute in the bridge's context. The host authenticates governance and\n///      writes its append-only reserve slot only after every read-only identity check succeeds.\nlibrary BridgeAccrualLib {\n    bytes32 private constant _MIXED_INTEREST_VERSION = keccak256(\"forestroad.mixed-interest.v1\");\n    /// @notice A proposed source does not identify the bridge's existing native module routes.\n\n    error BridgeAccrual_InvalidReserve(address reserve);\n\n    /// @notice Validates the token-first binding and both controller and native waterfall routes.\n    /// @param reserve The candidate accounting reserve proxy.\n    /// @param registry The bridge's already configured collateral registry.\n    /// @param oracle The bridge's already configured attestation oracle.\n    function validate(address reserve, address registry, address oracle) public view {\n        if (reserve.code.length == 0) revert BridgeAccrual_InvalidReserve(reserve);\n        bytes memory data = _reply(reserve, abi.encodeCall(IContinuousAccrual.accrualModules, ()), 224, reserve);\n        uint256[7] memory words = abi.decode(data, (uint256[7]));\n        for (uint256 i; i < 7; ++i) {\n            if (words[i] > type(uint160).max || address(uint160(words[i])).code.length == 0) {\n                revert BridgeAccrual_InvalidReserve(reserve);\n            }\n        }\n        IContinuousAccrual.Modules memory m = abi.decode(data, (IContinuousAccrual.Modules));\n        if (m.bridge != address(this) || m.registry != registry) revert BridgeAccrual_InvalidReserve(reserve);\n        data = _reply(m.token, abi.encodeCall(IAccrualToken.accrualReserve, ()), 32, reserve);\n        if (abi.decode(data, (uint256)) != uint256(uint160(reserve))) revert BridgeAccrual_InvalidReserve(reserve);\n        data = _reply(m.controller, abi.encodeCall(IMintRedeemController.modules, ()), 96, reserve);\n        uint256[3] memory controller = abi.decode(data, (uint256[3]));\n        if (\n            controller[0] != uint256(uint160(m.token)) || controller[1] > type(uint160).max\n                || controller[2] != uint256(uint160(reserve))\n        ) revert BridgeAccrual_InvalidReserve(reserve);\n        data = _reply(m.waterfall, abi.encodeWithSignature(\"modules()\"), 192, reserve);\n        uint256[6] memory waterfall = abi.decode(data, (uint256[6]));\n        if (\n            waterfall[0] != uint256(uint160(address(this))) || waterfall[1] != uint256(uint160(registry))\n                || waterfall[2] != uint256(uint160(reserve)) || waterfall[3] != uint256(uint160(m.controller))\n                || waterfall[4] != uint256(uint160(m.vault)) || waterfall[5] != uint256(uint160(oracle))\n        ) revert BridgeAccrual_InvalidReserve(reserve);\n        data = _reply(reserve, abi.encodeCall(IReserveManager.lossController, ()), 32, reserve);\n        if (abi.decode(data, (uint256)) != uint256(uint160(m.controller))) revert BridgeAccrual_InvalidReserve(reserve);\n    }\n\n    /// @notice Requires the reserve and bound waterfall to implement the same mixed-interest ABI.\n    function activateMixed(address reserve) public {\n        _requireMixedVersion(reserve, reserve);\n        bytes memory data = _reply(reserve, abi.encodeCall(IContinuousAccrual.accrualModules, ()), 224, reserve);\n        IContinuousAccrual.Modules memory m = abi.decode(data, (IContinuousAccrual.Modules));\n        if (m.bridge != address(this)) revert BridgeAccrual_InvalidReserve(reserve);\n        _requireMixedVersion(m.waterfall, reserve);\n        _requireMixedVersion(m.defaultManager, reserve);\n        IMixedInterestReserve(reserve).enableMixedInterest();\n    }\n\n    /// @notice Prevents a post-activation bridge downgrade to an implementation that cannot decode mixed state.\n    function validateMixedImplementation(address implementation) public view {\n        _requireMixedVersion(implementation, implementation);\n    }\n\n    function _requireMixedVersion(address target, address reported) private view {\n        bytes memory data = _reply(target, abi.encodeCall(IMixedInterestVersion.mixedInterestVersion, ()), 32, reported);\n        if (abi.decode(data, (bytes32)) != _MIXED_INTEREST_VERSION) {\n            revert BridgeAccrual_InvalidReserve(reported);\n        }\n    }\n\n    /// @dev Reject failed or malformed probes before decoding; no unchecked external result remains.\n    function _reply(address target, bytes memory request, uint256 length, address reserve)\n        private\n        view\n        returns (bytes memory data)\n    {\n        bool ok;\n        (ok, data) = target.staticcall(request);\n        if (!ok || data.length != length) revert BridgeAccrual_InvalidReserve(reserve);\n    }\n}\n"},{"file_path":"src/libraries/ReserveAccrualLib.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {ReserveManager} from \"../ReserveManager.sol\";\n\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {\n    IContinuousAccrual, IAccrualToken, IAccrualController, IAccrualVault\n} from \"../interfaces/IContinuousAccrual.sol\";\nimport {IWaterfallEngine} from \"../interfaces/IWaterfallEngine.sol\";\nimport {IMintRedeemController} from \"../interfaces/IMintRedeemController.sol\";\nimport {IERC4626} from \"@openzeppelin/contracts/interfaces/IERC4626.sol\";\nimport {AccrualBook} from \"./AccrualBook.sol\";\nimport {AccrualLoans} from \"./AccrualLoans.sol\";\nimport {AccrualCeiling} from \"./AccrualCeiling.sol\";\nimport {Config} from \"./Config.sol\";\nimport {ReserveAccrualStorageLib} from \"./ReserveAccrualStorageLib.sol\";\nimport {ReserveStorageLib} from \"./ReserveStorageLib.sol\";\n\ninterface IMixedReserveImplementation {\n    function mixedInterestVersion() external pure returns (bytes32);\n}\n\n/// @title ReserveAccrualLib\n/// @notice Reserve-owned continuous accounting configuration, views and exact physical delivery.\n/// @dev Public library methods execute in the reserve. Its host retains governance and reentrancy\n///      guards. All backing proofs use this reserve's own storage, independently of cached views.\nlibrary ReserveAccrualLib {\n    bytes32 private constant _MIXED_INTEREST_VERSION = keccak256(\"forestroad.mixed-interest.v1\");\n    /// @notice Preserves the credit adapter's existing cash-capacity error selector.\n\n    error AccrualCredit_ExposureCapacity();\n\n    /// @notice Capacity for the full signed obligation, with fixed cash or scheduled PIK terms.\n    /// @dev Shares one call encoding in the size-constrained credit adapter. For cash,\n    ///      frozenBasis is present principal and face additionally includes already-earned interest.\n    function loanCeiling(AccrualCeiling.Terms memory terms, bool pik) public pure returns (uint256 ceiling) {\n        if (pik) return AccrualCeiling.pik(terms);\n        uint256 principal = terms.frozenBasis;\n        if (principal > AccrualLoans.MAX_BASIS || terms.face < principal || terms.face > AccrualLoans.MAX_BASIS) {\n            revert AccrualCredit_ExposureCapacity();\n        }\n        if (terms.maturity <= terms.at) revert AccrualLoans.AccrualLoans_InvalidSchedule();\n        uint256 units =\n            Math.mulDiv(principal * terms.rateBps, terms.maturity - terms.at, terms.yearSeconds * 10_000 * terms.scale);\n        ceiling = terms.face;\n        if (units > (AccrualLoans.MAX_BASIS - ceiling) / terms.scale) revert AccrualCredit_ExposureCapacity();\n        return ceiling + units * terms.scale;\n    }\n\n    using AccrualBook for AccrualBook.Book;\n    using AccrualLoans for AccrualLoans.State;\n    using ReserveStorageLib for ReserveManager.ReserveStorage;\n\n    /// @notice Configuration is permanent and cannot replace existing obligations or nonce space.\n    error ReserveAccrual_AlreadyConfigured();\n    /// @notice Every bound address must be a compatible module of this instance.\n    error ReserveAccrual_WrongModules();\n    /// @notice Continuous accounting is not enabled yet.\n    error ReserveAccrual_NotEnabled();\n    /// @notice A coherent accounting operation is already in progress.\n    error ReserveAccrual_OperationInProgress();\n    /// @notice Activation cannot silently omit an existing deployed receivable.\n    error ReserveAccrual_MigrationRequired(uint256 deployed);\n    /// @notice Activation requires every frozen positive-face row to be imported and reconciled.\n    error ReserveAccrual_MigrationIncomplete(uint32 imported, uint32 expected);\n    /// @notice The configured interest fee exceeds its existing permanent limit.\n    error ReserveAccrual_InvalidFee(uint16 feeBps);\n    /// @notice The requested selected-claim mask must be senior=1, fee=2 or both=3.\n    error ReserveAccrual_InvalidLegs(uint8 legs);\n    /// @notice Vault share/fee accounting currently cannot admit neutral delivery.\n    error ReserveAccrual_VaultBusy();\n    /// @notice A delivery nonce cannot wrap or be reused.\n    error ReserveAccrual_NonceOverflow();\n    /// @notice Delivery must leave enough gas for the reserve's independent closing proofs.\n    error ReserveAccrual_InsufficientDeliveryGas(uint256 available);\n    /// @notice Actual physical or economic deltas did not match the exact permit.\n    error ReserveAccrual_DeliveryMismatch(uint8 measurement, uint256 expected, uint256 actual);\n    /// @notice Only the permanently bound waterfall can synchronize its configured interest fee.\n    error ReserveAccrual_NotWaterfall();\n    /// @notice Only the permanently bound bridge can atomically activate mixed facilities.\n    error ReserveAccrual_NotBridge();\n    /// @notice An activated proxy cannot downgrade to an incompatible implementation.\n    error ReserveAccrual_MixedVersionMismatch(address implementation);\n\n    /// @notice Immutable module identities were configured before activation.\n    event AccrualConfigured(address indexed token, address indexed controller, address indexed vault);\n    /// @notice Prospective continuous recognition was enabled at this timestamp and fee rate.\n    event AccrualEnabled(uint64 indexed at, uint16 feeBps, address feeRecipient);\n    /// @notice Selected existing senior/fee claims were physically delivered with exact delta proofs.\n    event AccrualMaterialized(uint256 indexed nonce, uint64 indexed at, uint8 legs, uint256 senior, uint256 fee);\n    /// @notice The old fee epoch closed before this rate or recipient became effective.\n    event AccrualFeeConfigured(uint16 feeBps, address indexed recipient, uint64 indexed at);\n    event MixedInterestEnabled(bytes32 indexed version);\n\n    /// @notice Installs immutable identities; the reserve host authenticates governance.\n    function configure(ReserveManager.ReserveStorage storage native, IContinuousAccrual.Modules memory m) public {\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        requireIdle();\n        if (s.modules.token != address(0)) revert ReserveAccrual_AlreadyConfigured();\n        if (\n            m.token.code.length == 0 || m.controller.code.length == 0 || m.vault.code.length == 0\n                || m.waterfall.code.length == 0 || m.bridge.code.length == 0 || m.registry.code.length == 0\n                || m.defaultManager.code.length == 0\n        ) revert ReserveAccrual_WrongModules();\n        if (\n            address(native.lossController) != m.controller || address(native.lossAbsorber) != m.defaultManager\n                || address(native.lossVault) != m.vault || address(native.lossUSDfr) != m.token\n        ) revert ReserveAccrual_WrongModules();\n        _validateRoutes(m, native);\n        if (\n            abi.decode(_reply(m.defaultManager, abi.encodeWithSignature(\"backstop()\"), 32), (uint256))\n                != uint256(uint160(address(native.lossBackstop)))\n        ) revert ReserveAccrual_WrongModules();\n        s.modules = m;\n        emit AccrualConfigured(m.token, m.controller, m.vault);\n    }\n\n    /// @notice Activates an empty book or a complete, reconciled opening import.\n    /// @dev A delayed import may have scheduled work due. Existing freshness gates continue to\n    ///      refuse financial entry until the normal keeper has processed those boundaries.\n    function enable(ReserveManager.ReserveStorage storage native) public {\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        if (s.busy || s.delivery.active) revert ReserveAccrual_OperationInProgress();\n        if (s.enabled) revert ReserveAccrual_AlreadyConfigured();\n        IContinuousAccrual.Modules memory m = s.modules;\n        requireConsumers(m);\n        uint256 deployed = native.totalDeployedPrincipal;\n        bool migrating = s.migration.active;\n        if (!migrating && deployed != 0) revert ReserveAccrual_MigrationRequired(deployed);\n        if (\n            migrating\n                && (\n                    s.migration.expected == 0 || s.migration.imported != s.migration.expected\n                        || s.migration.importedOriginalFace != s.migration.originalFace || s.recordedFace != deployed\n                )\n        ) {\n            revert ReserveAccrual_MigrationIncomplete(s.migration.imported, s.migration.expected);\n        }\n        uint16 feeBps = IWaterfallEngine(m.waterfall).protocolFeeBps();\n        if (feeBps > Config.MAX_PROTOCOL_FEE_BPS) revert ReserveAccrual_InvalidFee(feeBps);\n        address recipient = IWaterfallEngine(m.waterfall).feeRecipient();\n        if (recipient == address(0)) revert ReserveAccrual_WrongModules();\n        uint64 at = ReserveAccrualStorageLib.now64();\n        if (migrating) {\n            if (feeBps != s.migration.feeBps || recipient != s.feeRecipient) revert ReserveAccrual_WrongModules();\n            s.migration.active = false;\n        } else {\n            s.loans.initialize(at, feeBps);\n            s.feeRecipient = recipient;\n        }\n        s.enabled = true;\n        emit AccrualEnabled(at, feeBps, recipient);\n    }\n\n    /// @notice Irreversibly admits mixed facilities as one leg of the bridge's atomic activation.\n    function enableMixedInterest() public {\n        requireFresh();\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        if (msg.sender != s.modules.bridge) revert ReserveAccrual_NotBridge();\n        if (s.mixedInterestEnabled) revert ReserveAccrual_AlreadyConfigured();\n        s.mixedInterestEnabled = true;\n        emit MixedInterestEnabled(_MIXED_INTEREST_VERSION);\n    }\n\n    /// @notice Probes a prospective implementation after the irreversible feature latch is set.\n    function requireMixedImplementation(address implementation) public view {\n        if (!ReserveAccrualStorageLib.state().mixedInterestEnabled) return;\n        (bool ok, bytes memory data) =\n            implementation.staticcall(abi.encodeCall(IMixedReserveImplementation.mixedInterestVersion, ()));\n        if (!ok || data.length != 32 || abi.decode(data, (bytes32)) != _MIXED_INTEREST_VERSION) {\n            revert ReserveAccrual_MixedVersionMismatch(implementation);\n        }\n    }\n\n    /// @notice Every bound consumer must point back to this native reserve before preparation.\n    function requireConsumers(IContinuousAccrual.Modules memory m) internal view {\n        if (\n            m.token == address(0) || IAccrualToken(m.token).accrualReserve() != address(this)\n                || IAccrualVault(m.vault).accrualReserve() != address(this)\n                || IAccrualVault(m.controller).accrualReserve() != address(this)\n                || IAccrualVault(m.waterfall).accrualReserve() != address(this)\n                || IAccrualVault(m.bridge).accrualReserve() != address(this)\n                || IAccrualVault(m.registry).accrualReserve() != address(this)\n                || IAccrualVault(m.defaultManager).accrualReserve() != address(this)\n        ) revert ReserveAccrual_WrongModules();\n    }\n\n    /// @notice Synchronizes both fee fields prospectively, delivering an old recipient's claim first.\n    /// @dev The waterfall updates its own fields after this returns. A failure rolls back both sides.\n    function setFee(ReserveManager.ReserveStorage storage native, uint16 feeBps, address recipient) public {\n        requireFresh();\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        if (msg.sender != s.modules.waterfall) revert ReserveAccrual_NotWaterfall();\n        if (!s.enabled) revert ReserveAccrual_NotEnabled();\n        if (feeBps > Config.MAX_PROTOCOL_FEE_BPS) revert ReserveAccrual_InvalidFee(feeBps);\n        if (recipient == address(0) || !IMintRedeemController(s.modules.controller).isYieldSink(recipient)) {\n            revert ReserveAccrual_WrongModules();\n        }\n        if (recipient != s.feeRecipient) materialize(native, 2);\n        uint64 at = ReserveAccrualStorageLib.now64();\n        s.loans.book.setFee(feeBps, at);\n        s.feeRecipient = recipient;\n        emit AccrualFeeConfigured(feeBps, recipient, at);\n    }\n\n    /// @notice Delivers the vault's existing claims before a native cascade can burn its assets.\n    /// @dev A separate fee recipient retains its fully earned claim for permissionless delivery;\n    ///      restrictions on that recipient cannot hold an unrelated loss or repayment hostage.\n    ///      If the vault owns the fee too, both legs belong to its loss-absorbing assets. The\n    ///      native loss manager retains its established pre-loss performance-fee checkpoint.\n    function prepareNativeLoss(ReserveManager.ReserveStorage storage native) public {\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        if (s.enabled) materialize(native, s.feeRecipient == s.modules.vault ? 3 : 1);\n    }\n\n    /// @dev Verify all forward routes before the permanent tuple can strand a consumer binding.\n    ///      Consumer reverse bindings are necessarily installed afterwards and checked at activation.\n    function _validateRoutes(IContinuousAccrual.Modules memory m, ReserveManager.ReserveStorage storage native)\n        private\n        view\n    {\n        uint256[3] memory c = abi.decode(_reply(m.controller, abi.encodeWithSignature(\"modules()\"), 96), (uint256[3]));\n        if (c[0] != uint256(uint160(m.token)) || c[1] > type(uint160).max || c[2] != uint256(uint160(address(this)))) {\n            revert ReserveAccrual_WrongModules();\n        }\n        if (abi.decode(_reply(m.vault, abi.encodeCall(IERC4626.asset, ()), 32), (uint256)) != uint256(uint160(m.token)))\n        {\n            revert ReserveAccrual_WrongModules();\n        }\n        uint256[2] memory b = abi.decode(_reply(m.bridge, abi.encodeWithSignature(\"modules()\"), 64), (uint256[2]));\n        if (b[0] != uint256(uint160(m.registry)) || b[1] > type(uint160).max || address(uint160(b[1])).code.length == 0)\n        {\n            revert ReserveAccrual_WrongModules();\n        }\n        uint256[6] memory w = abi.decode(_reply(m.waterfall, abi.encodeWithSignature(\"modules()\"), 192), (uint256[6]));\n        if (\n            w[0] != uint256(uint160(m.bridge)) || w[1] != uint256(uint160(m.registry))\n                || w[2] != uint256(uint160(address(this))) || w[3] != uint256(uint160(m.controller))\n                || w[4] != uint256(uint160(m.vault)) || w[5] != b[1]\n                || abi.decode(_reply(m.waterfall, abi.encodeWithSignature(\"defaultManager()\"), 32), (uint256))\n                    != uint256(uint160(m.defaultManager))\n        ) revert ReserveAccrual_WrongModules();\n        uint256[8] memory d =\n            abi.decode(_reply(m.defaultManager, abi.encodeWithSignature(\"modules()\"), 256), (uint256[8]));\n        if (\n            d[0] != uint256(uint160(m.bridge)) || d[1] != uint256(uint160(m.registry))\n                || d[2] != uint256(uint160(address(this))) || d[3] != uint256(uint160(m.controller))\n                || d[4] != uint256(uint160(address(native.lossCurator))) || d[5] != b[1]\n                || d[6] != uint256(uint160(m.vault)) || d[7] > type(uint160).max || address(uint160(d[7])).code.length == 0\n        ) revert ReserveAccrual_WrongModules();\n    }\n\n    function _reply(address target, bytes memory request, uint256 length) private view returns (bytes memory data) {\n        bool ok;\n        (ok, data) = target.staticcall(request);\n        if (!ok || data.length != length) revert ReserveAccrual_WrongModules();\n    }\n\n    /// @notice The authoritative price-write admission gate, including non-delivery host operations.\n    function requireFresh() public view {\n        requireIdle();\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        if (s.enabled) s.loans.book.requireFresh(ReserveAccrualStorageLib.now64());\n    }\n\n    /// @notice Refuses an overlapping accounting operation without blocking clock-independent recovery.\n    function requireIdle() internal view {\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        if (s.busy || s.delivery.active || s.migration.active) revert ReserveAccrual_OperationInProgress();\n    }\n\n    /// @notice Public coherent snapshot; off mode is zero and fresh.\n    function snapshot() internal view returns (IContinuousAccrual.Snapshot memory result) {\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        if (s.migration.active) revert ReserveAccrual_OperationInProgress();\n        if (s.delivery.active) return s.deliverySnapshot;\n        uint64 at = ReserveAccrualStorageLib.now64();\n        result.feeRecipient = s.feeRecipient;\n        result.enabled = s.enabled;\n        result.fresh = true;\n        result.accruedThrough = at;\n        if (!s.enabled) return result;\n        AccrualBook.Snapshot memory book = s.loans.book.snapshot(at);\n        result.gross = book.gross;\n        result.unposted = book.unposted;\n        result.unissued = book.unissued;\n        result.seniorUnissued = book.seniorUnissued;\n        result.feeUnissued = book.feeUnissued;\n        result.accruedThrough = book.accruedThrough;\n        result.fresh = book.fresh;\n    }\n\n    /// @notice Compiler-encoded public snapshot, forwarded by the host without a redundant decode.\n    function snapshotData() public view returns (bytes memory) {\n        return abi.encode(snapshot());\n    }\n\n    /// @notice Compiler-encoded immutable module tuple for the host's existing external ABI.\n    function modulesData() public view returns (bytes memory) {\n        return abi.encode(ReserveAccrualStorageLib.state().modules);\n    }\n\n    /// @notice Compiler-encoded delivery tuple; inactive delivery retains its all-zero ABI shape.\n    function deliveryData() public view returns (bytes memory) {\n        IContinuousAccrual.Delivery memory result;\n        IContinuousAccrual.Delivery storage delivery = ReserveAccrualStorageLib.state().delivery;\n        if (delivery.active) result = delivery;\n        return abi.encode(result);\n    }\n\n    /// @notice Converts selected previously recognized liabilities into physical token balances.\n    /// @dev No vault write callback, facility scan, new recognition or headroom clamp occurs.\n    function materialize(ReserveManager.ReserveStorage storage native, uint8 legs)\n        public\n        returns (uint256 senior, uint256 fee)\n    {\n        requireFresh();\n        if (legs == 0 || legs > 3) revert ReserveAccrual_InvalidLegs(legs);\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        if (!s.enabled) revert ReserveAccrual_NotEnabled();\n        IContinuousAccrual.Snapshot memory beforeBook = snapshot();\n        senior = (legs & 1) == 0 ? 0 : beforeBook.seniorUnissued;\n        fee = (legs & 2) == 0 ? 0 : beforeBook.feeUnissued;\n        if (senior == 0 && fee == 0) return (0, 0);\n        IContinuousAccrual.Delivery memory d;\n        d.pricing = IAccrualVault(s.modules.vault).accrualPricingState();\n        if (!d.pricing.materializationAllowed) revert ReserveAccrual_VaultBusy();\n        if (s.nonce == type(uint256).max) revert ReserveAccrual_NonceOverflow();\n        d.nonce = ++s.nonce;\n        d.senior = senior;\n        d.fee = fee;\n        d.controller = s.modules.controller;\n        d.vault = s.modules.vault;\n        d.feeRecipient = s.feeRecipient;\n        d.accruedThrough = beforeBook.accruedThrough;\n        d.legs = legs;\n        d.active = true;\n        uint256[3] memory rawBefore = _rawBalances(s.modules.token, d.vault, d.feeRecipient);\n        d.effectiveSupply = rawBefore[0] + beforeBook.unissued;\n        (d.backing, d.recognizedBacking) = rawBacking(native);\n        s.delivery = d;\n        s.deliverySnapshot = beforeBook;\n        s.busy = true;\n        s.loans.book.takeIssuance(legs, beforeBook.accruedThrough);\n        _deliver(d.controller, d.nonce);\n        _proveDelivery(s, native, d, rawBefore);\n        delete s.delivery;\n        delete s.deliverySnapshot;\n        s.busy = false;\n        emit AccrualMaterialized(d.nonce, d.accruedThrough, legs, senior, fee);\n    }\n\n    /// @notice Independently reads native accounting; delivery snapshots are deliberately ignored.\n    function rawBacking(ReserveManager.ReserveStorage storage native)\n        internal\n        view\n        returns (uint256 backing, uint256 recognized)\n    {\n        backing = native.backingValue();\n        uint256 live = native.usdcToken.balanceOf(address(this));\n        uint256 shortfall = native.idleUSDCUnits > live ? ReserveStorageLib.normalize(native.idleUSDCUnits - live) : 0;\n        recognized = backing > shortfall ? backing - shortfall : 0;\n    }\n\n    function _rawBalances(address token, address vault, address feeRecipient)\n        private\n        view\n        returns (uint256[3] memory values)\n    {\n        IERC20 usdfr = IERC20(token);\n        values[0] = usdfr.totalSupply();\n        values[1] = usdfr.balanceOf(vault);\n        values[2] = feeRecipient == vault ? values[1] : usdfr.balanceOf(feeRecipient);\n    }\n\n    /// @dev A failed optional token hook must not consume the caller's proof/cleanup budget.\n    ///      This reserves continuation gas; it does not impose a fixed cap on token work.\n    function _deliver(address controller, uint256 nonce) private {\n        uint256 available = gasleft();\n        uint256 retained = available >> 3;\n        if (retained < 350_000) retained = 350_000;\n        if (available <= retained + 200_000) revert ReserveAccrual_InsufficientDeliveryGas(available);\n        IAccrualController(controller).mintAccrued{gas: available - retained}(nonce);\n    }\n\n    function _proveDelivery(\n        ReserveAccrualStorageLib.State storage s,\n        ReserveManager.ReserveStorage storage native,\n        IContinuousAccrual.Delivery memory d,\n        uint256[3] memory before_\n    ) private view {\n        uint256[3] memory after_ = _rawBalances(s.modules.token, d.vault, d.feeRecipient);\n        _equal(0, before_[0] + d.senior + d.fee, after_[0]);\n        uint256 vaultMinted = d.senior + (d.feeRecipient == d.vault ? d.fee : 0);\n        _equal(1, before_[1] + vaultMinted, after_[1]);\n        if (d.feeRecipient != d.vault) _equal(2, before_[2] + d.fee, after_[2]);\n        AccrualBook.Snapshot memory book = s.loans.book.snapshot(d.accruedThrough);\n        _equal(3, d.effectiveSupply, after_[0] + book.unissued);\n        uint256 owned = book.seniorUnissued + (d.feeRecipient == d.vault ? book.feeUnissued : 0);\n        _equal(4, d.pricing.entryAssets, after_[1] + owned);\n        (uint256 backing, uint256 recognized) = rawBacking(native);\n        _equal(5, d.backing, backing);\n        _equal(6, d.recognizedBacking, recognized);\n    }\n\n    function _equal(uint8 measurement, uint256 expected, uint256 actual) private pure {\n        if (expected != actual) revert ReserveAccrual_DeliveryMismatch(measurement, expected, actual);\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.20;\n\nimport {SafeCast} from \"./SafeCast.sol\";\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n    /**\n     * @dev Branchless ternary evaluation for `a ? b : c`. 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. `a ? b : c`) to only compute\n     * one branch when needed, making this function more expensive.\n     */\n    function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {\n        unchecked {\n            // branchless ternary works because:\n            // b ^ (a ^ b) == a\n            // b ^ 0 == b\n            return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));\n        }\n    }\n\n    /**\n     * @dev Returns the largest of two signed numbers.\n     */\n    function max(int256 a, int256 b) internal pure returns (int256) {\n        return ternary(a > b, a, b);\n    }\n\n    /**\n     * @dev Returns the smallest of two signed numbers.\n     */\n    function min(int256 a, int256 b) internal pure returns (int256) {\n        return ternary(a < b, a, b);\n    }\n\n    /**\n     * @dev Returns the average of two signed numbers without overflow.\n     * The result is rounded towards zero.\n     */\n    function average(int256 a, int256 b) internal pure returns (int256) {\n        // Formula from the book \"Hacker's Delight\"\n        int256 x = (a & b) + ((a ^ b) >> 1);\n        return x + (int256(uint256(x) >> 255) & (a ^ b));\n    }\n\n    /**\n     * @dev Returns the absolute unsigned value of a signed value.\n     */\n    function abs(int256 n) internal pure returns (uint256) {\n        unchecked {\n            // Formula from the \"Bit Twiddling Hacks\" by Sean Eron Anderson.\n            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,\n            // taking advantage of the most significant (or \"sign\" bit) in two's complement representation.\n            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,\n            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).\n            int256 mask = n >> 255;\n\n            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.\n            return uint256((n + mask) ^ mask);\n        }\n    }\n}\n"},{"file_path":"src/libraries/ReserveCreditLib.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\nimport {IReserveManager} from \"../interfaces/IReserveManager.sol\";\nimport {ReserveManager} from \"../ReserveManager.sol\";\nimport {ReserveStorageLib} from \"./ReserveStorageLib.sol\";\nimport {BorrowerPayoutLib} from \"./BorrowerPayoutLib.sol\";\n\n/// @title ReserveCreditLib — the ReserveManager's credit-path bodies\n///\n/// @notice EXTRACTED 2026-09-09 FOR EIP-170, mirroring BSC commit `9438be1`. The live mainnet\n///         `ReserveManager` shipped with 9 bytes of runtime margin, so it was frozen against any\n///         new function; adding `recordPikCapitalization` put it 184 bytes over the 24,576 limit\n///         even after the fee and PIK twins were made to share one private body.\n///\n/// @dev EVERY FUNCTION HERE IS `public` AND THAT IS THE WHOLE POINT. A `public` library function is\n///      deployed as its own contract and reached by delegatecall, so its bytecode leaves the\n///      caller's runtime; an `internal` one is inlined and saves nothing. The library therefore\n///      needs LINKING at deploy time, which is new for this repository.\n///\n/// @dev THE CALLER KEEPS THE GUARDS. `ReserveManager` retains every `onlyRole`, `nonReentrant` and\n///      `whenNotPaused` modifier on the external entry points, because a delegatecall runs in the\n///      proxy's context and a library cannot see the caller's modifiers. Do not call anything here\n///      from a path that does not carry them.\n///\n/// @dev DELEGATECALL MEANS `address(this)` IS THE PROXY, which is what keeps `safeTransfer`,\n///      `balanceOf(address(this))` and the self-deployment guard meaning exactly what they meant\n///      when these bodies lived in the contract.\nlibrary ReserveCreditLib {\n    /// @notice Principal and previously recognized interest discharged by measured canonical USDC.\n    event AccruedPaymentReceived(\n        uint256 indexed facilityId,\n        address indexed asset,\n        address indexed payer,\n        uint256 nativeUnits,\n        uint256 principalReduction,\n        uint256 interestReduction\n    );\n\n    using SafeERC20 for IERC20;\n    using ReserveStorageLib for ReserveManager.ReserveStorage;\n\n    /// @dev Body of `ReserveManager.recordDeployment`.\n    function deploy(ReserveManager.ReserveStorage storage $, uint256 facilityId, address to, uint256 usdcAmount)\n        public\n    {\n        if (to == address(0)) revert IReserveManager.ReserveManager_ZeroAddress();\n        if (to == address(this)) revert IReserveManager.ReserveManager_SelfDeployment();\n        if (usdcAmount == 0) revert IReserveManager.ReserveManager_ZeroAmount();\n        BorrowerPayoutLib.requireAllowedInternal(to);\n        // MA-1/R4-01: a live custody shortfall freezes the facility-funding USDC out-door.\n        $.requireIdleFullyCustodied();\n        uint256 value = ReserveStorageLib.normalize(usdcAmount);\n        uint256 idleValue = ReserveStorageLib.normalize($.idleUSDCUnits);\n        if (value > idleValue) revert IReserveManager.ReserveManager_InsufficientIdleValue(value, idleValue);\n        $.idleUSDCUnits -= usdcAmount;\n        $.deployed[facilityId] += value;\n        $.totalDeployedPrincipal += value;\n        $.usdcToken.safeTransfer(to, usdcAmount);\n        emit IReserveManager.PrincipalDeployed(facilityId, value);\n    }\n\n    /// @dev Shared body of `recordFeeCapitalization` and `recordPikCapitalization`. `requireIdle`\n    ///      is the fee twin's solvency bound; PIK has no cash behind it and passes false.\n    ///\n    ///      The fee twin is sound because the fee's cash NEVER LEFT: `fund` deploys\n    ///      `principal - fee`, so backing rises against RETAINED CASH and bounding it by idle is\n    ///      meaningful. There is no retained cash behind a PIK capitalisation; what stands behind\n    ///      it is the borrower's obligation to repay a larger balance and, beneath that, the\n    ///      curator first-loss layer. Bounding a receivable by idle cash would refuse a legitimate\n    ///      capitalisation on a drawn-down book and admit one on a flush book.\n    ///\n    ///      EVERY OTHER BOUND ON PIK LIVES IN `WaterfallEngine.capitalizePik`.\n    function capitalize(ReserveManager.ReserveStorage storage $, uint256 facilityId, uint256 amount, bool requireIdle)\n        public\n    {\n        if (amount == 0) revert IReserveManager.ReserveManager_ZeroAmount();\n        uint256 units = ReserveStorageLib.denormalize(amount);\n        if (ReserveStorageLib.normalize(units) != amount) {\n            revert IReserveManager.ReserveManager_ValueNotUSDCExact(amount);\n        }\n        if (requireIdle) {\n            uint256 idleValue = ReserveStorageLib.normalize($.idleUSDCUnits);\n            if (amount > idleValue) revert IReserveManager.ReserveManager_InsufficientIdleValue(amount, idleValue);\n        }\n        // The borrower owes the full face amount while the OID cash stays in the treasury (fee\n        // path) or while the interest compounds into principal (PIK path). Both are additional\n        // receivable; only the fee path has retained cash standing behind it.\n        $.deployed[facilityId] += amount;\n        $.totalDeployedPrincipal += amount;\n        if (requireIdle) {\n            emit IReserveManager.FeeCapitalized(facilityId, amount);\n        } else {\n            emit IReserveManager.PikCapitalized(facilityId, amount, $.deployed[facilityId]);\n        }\n    }\n\n    /// @dev Body of `ReserveManager.recordPayment`.\n    function pay(\n        ReserveManager.ReserveStorage storage native,\n        uint256 facilityId,\n        address payer,\n        uint256 usdcAmount,\n        uint256 principal\n    ) public returns (uint256 receivedValue) {\n        receivedValue = _pay(native, facilityId, payer, usdcAmount, principal);\n        emit IReserveManager.PaymentReceived(facilityId, payer, usdcAmount, principal);\n    }\n\n    /// @notice A measured receipt replaces already recognized cash or PIK receivable, without new income.\n    function payAccrued(\n        ReserveManager.ReserveStorage storage native,\n        uint256 facilityId,\n        address payer,\n        uint256 usdcAmount,\n        uint256 principalReduction,\n        uint256 interestReduction\n    ) public returns (uint256 receivedValue) {\n        receivedValue = _pay(native, facilityId, payer, usdcAmount, principalReduction + interestReduction);\n        emit AccruedPaymentReceived(\n            facilityId, address(native.usdcToken), payer, usdcAmount, principalReduction, interestReduction\n        );\n    }\n\n    function _pay(\n        ReserveManager.ReserveStorage storage $,\n        uint256 facilityId,\n        address payer,\n        uint256 usdcAmount,\n        uint256 principal\n    ) private returns (uint256 receivedValue) {\n        if (payer == address(0)) revert IReserveManager.ReserveManager_ZeroAddress();\n        if (usdcAmount == 0) revert IReserveManager.ReserveManager_ZeroAmount();\n        uint256 beforeBalance = $.usdcToken.balanceOf(address(this));\n        $.usdcToken.safeTransferFrom(payer, address(this), usdcAmount);\n        uint256 received = $.usdcToken.balanceOf(address(this)) - beforeBalance;\n        if (received != usdcAmount) {\n            revert IReserveManager.ReserveManager_UnexpectedUSDCReceipt(usdcAmount, received);\n        }\n        receivedValue = ReserveStorageLib.normalize(received);\n        if (principal > receivedValue) {\n            revert IReserveManager.ReserveManager_PrincipalExceedsPayment(principal, receivedValue);\n        }\n        uint256 deployedFace = $.deployed[facilityId];\n        if (principal > deployedFace) {\n            revert IReserveManager.ReserveManager_InsufficientDeployedPrincipal(facilityId, principal, deployedFace);\n        }\n        $.idleUSDCUnits += received;\n        if (principal != 0) {\n            uint256 remainingFace = deployedFace - principal;\n            $.deployed[facilityId] = remainingFace;\n            $.totalDeployedPrincipal -= principal;\n            // H-1: cash collection does not prove that a governance-adjudicated impairment\n            // was recovered. Preserve the mark unless the smaller remaining face can no longer\n            // support it; only that arithmetically unavoidable excess is released. Treating\n            // every repayment dollar as recovery made backing depend on repayment/write-down\n            // ordering and could silently reopen par exits against the still-impaired claim.\n            $.clampImpairmentToRemainingFace(facilityId, remainingFace);\n        }\n    }\n\n    /// @dev Body of `ReserveManager.recordPrincipalWritedown`. Extracted with the credit path\n    ///      because it shares the impairment helpers with `pay`.\n    function writeDown(ReserveManager.ReserveStorage storage $, uint256 facilityId, uint256 amount) public {\n        if (amount == 0) revert IReserveManager.ReserveManager_ZeroAmount();\n        uint256 deployedFace = $.deployed[facilityId];\n        if (amount > deployedFace) {\n            revert IReserveManager.ReserveManager_InsufficientDeployedPrincipal(facilityId, amount, deployedFace);\n        }\n        $.deployed[facilityId] = deployedFace - amount;\n        $.totalDeployedPrincipal -= amount;\n        // A write-down is the realization of loss, so the mark already carried against that\n        // loss must be consumed to avoid counting the same dollar twice.\n        $.realizeImpairmentOnWriteDown(facilityId, amount);\n        emit IReserveManager.PrincipalWrittenDown(facilityId, amount);\n    }\n}\n"},{"file_path":"src/interfaces/IAttestationOracle.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\n/// @title IAttestationOracle\n/// @notice Off-chain → on-chain synchronization layer (ADR-0007). Facilities may not\n///         mint, and material state may not advance, without the required attestations.\n/// @dev TRUST NOTE (state prominently everywhere): the protocol executes faithfully on\n///      whatever authorized attesters assert. A false attestation or compromised\n///      attester key means the protocol acts on false information. This is the\n///      protocol's primary trust assumption (ADR-0007; brief Part 11 gate 6).\ninterface IAttestationOracle {\n    /// @notice Attestation kinds, per ADR-0007 / the legal-wrapper sync table.\n    enum AttestationKind {\n        AssignmentExecuted,\n        UCCFiled,\n        CreditIssued,\n        PaymentReceived,\n        DefaultDeclared,\n        Valuation,\n        LossRealized,\n        PastDueCured,\n        TermsAmended,\n        /// @dev One-shot opening debt for continuous accrual. The payload binds the reserve,\n        ///      migration session, cutoff, facility identity, contractual cursor and balances.\n        AccrualOpening\n    }\n\n    /// @notice Lifecycle of a single ECONOMIC FACT, keyed by (facilityId, kind, payload).\n    /// @dev AUDIT FIX (C4-01/C4-02). This enum exists because the EIP-712 DIGEST is the wrong\n    ///      uniqueness key: `nonce`, `asOf` and `expiry` are all inside the digest but outside the\n    ///      fact, so the SAME real-world event re-signed under a fresh nonce produced a fresh\n    ///      digest and sailed past `used[digest]`. The fact key is digest-independent, so a fact\n    ///      leaves `None` exactly once and never returns to it. See `attest`.\n    /// @custom:member None Never recorded — the only state from which `attest` accepts the fact.\n    /// @custom:member Recorded Accepted and standing; the credit layer has not spent it yet.\n    /// @custom:member Consumed Spent by a CREDIT_ROLE module (the write-down/distribution ran).\n    /// @custom:member Revoked Governance killed it (C4-02: a DURABLE tombstone, not just a flag).\n    enum FactStatus {\n        None,\n        Recorded,\n        Consumed,\n        Revoked\n    }\n\n    /// @notice One attested fact, signed by m-of-n authorized attesters over EIP-712.\n    /// @param facilityId The facility.\n    /// @param kind The attestation kind.\n    /// @param payload Kind-specific commitment. Valuation stores the 18-decimal value\n    ///        directly; operational facts commit to their complete action parameters\n    ///        (terms, payment id/payer/amounts/due date, evidence hash, or amendment id).\n    /// @param asOf The ATTESTED observation time (inside the signed payload — not the\n    ///        submission block time; freshness rules depend on this, ADR-0017 §4).\n    /// @param expiry Submission deadline for this signed bundle.\n    /// @param nonce Uniqueness salt (any unused value; digests are consume-once).\n    struct AttestationInput {\n        uint256 facilityId;\n        AttestationKind kind;\n        bytes32 payload;\n        uint64 asOf;\n        uint64 expiry;\n        uint256 nonce;\n    }\n\n    // ── Events ───────────────────────────────────────────────────────────\n    /// @notice Emitted once per recovered signer of an accepted attestation.\n    event Attested(uint256 indexed facilityId, AttestationKind indexed kind, address indexed attester, uint64 at);\n    /// @notice The fact is now on-chain truth (threshold met).\n    event AttestationSatisfied(uint256 indexed facilityId, AttestationKind indexed kind, bytes32 payload, uint64 asOf);\n    /// @notice A one-shot fact was consumed by the credit layer (e.g. a\n    ///         PaymentReceived spent by its distribution).\n    event AttestationConsumed(uint256 indexed facilityId, AttestationKind indexed kind, address indexed by);\n    /// @notice Governance revoked a fact (e.g. discovered-false attestation).\n    event AttestationRevoked(uint256 indexed facilityId, AttestationKind indexed kind);\n    event ThresholdSet(AttestationKind indexed kind, uint8 threshold);\n    // NOTE: `ValuationWatermarkReset` and the `resetValuationWatermark` lever were REMOVED\n    // (owner decision 2026-07-22). The H-02 anti-rollback watermark itself is unchanged; a stuck\n    // watermark is recovered via the oracle's timelocked UUPS upgrade, not a dedicated lever.\n\n    // ── Errors ───────────────────────────────────────────────────────────\n    error Oracle_Expired(uint64 expiry);\n    error Oracle_BadAsOf(uint64 asOf);\n    error Oracle_DigestAlreadyUsed(bytes32 digest);\n    error Oracle_ThresholdNotMet(uint8 required, uint256 provided);\n    error Oracle_NotAttester(address recovered);\n    error Oracle_UnorderedSigners(address prev, address current);\n    error Oracle_ZeroValuation();\n    error Oracle_StaleValuation(uint64 asOf, uint64 existing);\n    error Oracle_NotSatisfied(uint256 facilityId, AttestationKind kind);\n    /// @notice Process or revoke the current action before submitting another of the same kind.\n    error Oracle_UnconsumedFact(uint256 facilityId, AttestationKind kind, bytes32 payload);\n    error Oracle_BadThreshold();\n    /// @notice AUDIT FIX (C4-01/C4-02): this economic fact has already left `None`. It was\n    ///         recorded, spent, or revoked, and no re-signing under a fresh nonce brings it back.\n    /// @param factKey keccak256(abi.encode(facilityId, uint8(kind), payload)) — see `factKey`.\n    /// @param status The terminal-for-`attest` state the fact is already in.\n    error Oracle_FactAlreadyRealised(bytes32 factKey, FactStatus status);\n\n    // ── Submission (permissionless relay of attester signatures) ─────────\n    /// @notice Records `a` as on-chain truth if at least the kind's threshold of\n    ///         DISTINCT authorized attesters signed exactly this struct (EIP-712).\n    ///         Anyone may relay the bundle; the signatures are the authority.\n    function attest(AttestationInput calldata a, bytes[] calldata signatures) external;\n\n    // ── Credit-layer consumption ─────────────────────────────────────────\n    /// @notice Clears the satisfied flag of a one-shot fact (payload/asOf retained\n    ///         for audit). Only a wired CREDIT_ROLE module may consume a fact.\n    function consume(uint256 facilityId, AttestationKind kind) external;\n\n    // ── Governance ───────────────────────────────────────────────────────\n    /// @notice Revokes a fact (clears satisfied; a revoked Valuation is zeroed so the\n    ///         margin path blocks until a fresh mark). Timelocked governance only.\n    function revoke(uint256 facilityId, AttestationKind kind) external;\n\n    // NOTE (owner decision 2026-07-22): the `resetValuationWatermark` recovery lever was REMOVED.\n    // The H-02 anti-rollback watermark itself is unchanged. Rationale: the lever was also an\n    // attack surface -- governance goes through a PUBLIC timelock queue, so a queued reset let a\n    // holder of a pre-signed OLDER valuation race the watermark down the instant it executed,\n    // re-opening the rollback the watermark prevents. The rare \"watermark stuck at a far-future\n    // asOf after an attester-quorum compromise\" recovery is instead handled by the oracle's\n    // timelocked UUPS upgrade (redundant with the lever, without the race surface). This\n    // supersedes the 2026-07-21 decision to keep it.\n\n    /// @notice Sets a kind's m-of-n threshold (>= 1). Timelocked governance only.\n    function setThreshold(AttestationKind kind, uint8 threshold_) external;\n\n    // ── Views ────────────────────────────────────────────────────────────\n    /// @notice True if `facilityId` has a currently valid attestation of `kind`.\n    function isSatisfied(uint256 facilityId, AttestationKind kind) external view returns (bool);\n\n    /// @notice Latest attested valuation mark for a facility (conservative, haircut).\n    /// @return value 18-dec USD mark (0 = no valid mark).\n    /// @return asOf Attested observation time of the mark (staleness checks per\n    ///         ADR-0015 for marked-to-market classes).\n    function latestValuation(uint256 facilityId) external view returns (uint256 value, uint64 asOf);\n\n    /// @notice Latest recorded fact for (facility, kind).\n    function latestPayload(uint256 facilityId, AttestationKind kind)\n        external\n        view\n        returns (bytes32 payload, uint64 asOf, bool satisfied);\n\n    /// @notice The facility's valuation anti-rollback high-watermark: the highest attested\n    ///         `asOf` ever ACCEPTED for this facility, preserved across `revoke` and `consume`.\n    ///         A new `Valuation` must beat it strictly.\n    /// @param facilityId The facility identifier.\n    /// @return highestAsOf Highest accepted observation time (0 = never marked).\n    function valuationWatermark(uint256 facilityId) external view returns (uint64 highestAsOf);\n\n    /// @notice Current m-of-n threshold for a kind.\n    function threshold(AttestationKind kind) external view returns (uint8);\n\n    /// @notice True if an attestation digest was already submitted (replay guard).\n    /// @dev NOT a fact-uniqueness guard — it is defeated by re-signing the same fact under a\n    ///      fresh nonce. Read `factStatus` for \"has this real-world event already been realised\".\n    function digestUsed(bytes32 digest) external view returns (bool);\n\n    /// @notice The consume-once key for an economic fact: the (facility, kind, payload) triple,\n    ///         with the digest's replay salt (`nonce`/`asOf`/`expiry`) DELIBERATELY excluded.\n    /// @dev AUDIT FIX (C4-01). Exposed so relayers and attester tooling can check whether a fact\n    ///      is already spent before paying for signatures.\n    /// @param facilityId The facility the fact concerns.\n    /// @param kind The attestation kind.\n    /// @param payload The kind-specific commitment identifying the real-world event.\n    /// @return key keccak256(abi.encode(facilityId, uint8(kind), payload)).\n    function factKey(uint256 facilityId, AttestationKind kind, bytes32 payload) external pure returns (bytes32 key);\n\n    /// @notice Lifecycle state of one economic fact (C4-01/C4-02). `None` is the only state from\n    ///         which `attest` accepts it; the transition out of `None` is irreversible.\n    /// @dev Always `None` for `Valuation`: a valuation is a monotone OBSERVATION SERIES, not a\n    ///      one-shot event, and its uniqueness key is `valuationWatermark`, not the payload. Two\n    ///      genuinely distinct marks may legitimately carry the identical value.\n    /// @param facilityId The facility the fact concerns.\n    /// @param kind The attestation kind.\n    /// @param payload The kind-specific commitment identifying the real-world event.\n    /// @return status `None` if never realised; otherwise `Recorded`, `Consumed` or `Revoked`.\n    function factStatus(uint256 facilityId, AttestationKind kind, bytes32 payload)\n        external\n        view\n        returns (FactStatus status);\n\n    /// @notice The EIP-712 digest attesters sign for `a`.\n    /// @dev Exposed for signing tools, atomic executors, and replay-safe relayers.\n    function attestationDigest(AttestationInput calldata a) external view returns (bytes32);\n}\n"},{"file_path":"src/libraries/AccrualSegments.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport {AccrualMath} from \"./AccrualMath.sol\";\n\n/// @title AccrualSegments\n/// @notice Pure fixed-basis entitlement and bounded technical-segment planning.\n/// @dev The host supplies authenticated fixed Actual/360 or Actual/365 terms and controls PIK\n///      capitalization, cap changes and lifecycle authority. Technical splits never rebase PIK.\n///      Cumulative endpoints round the original period's simple interest to the reserve grid;\n///      adjacent differences telescope exactly. Interpolating those endpoints is a different\n///      partial-time curve from rounding the original simple interest at that instant. Use\n///      cumulative for authoritative contractual settlement and handle any discrepancy explicitly\n///      in the host's backing/loss accounting. This library makes no such financial-policy choice.\n///      It has no state, clock reads, roles, external calls or effects.\nlibrary AccrualSegments {\n    /// @notice Maximum technical interpolation duration; contractual intervals may be longer.\n    uint64 internal constant MAX_SEGMENT_SECONDS = 365 days;\n\n    /// @notice Cached fixed terms for one contractual interest period.\n    /// @dev cap is the maximum additional interest for this period, not a total loan balance.\n    ///      A technical successor must retain this same basis and periodStart. The host alone\n    ///      changes them at a proved contractual transition. Maturity may truncate periodEnd.\n    /// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.\n    struct Terms {\n        uint256 basis;\n        uint256 yearSeconds;\n        uint256 scale;\n        uint256 cap;\n        uint64 periodStart;\n        uint64 periodEnd;\n        uint64 maturity;\n        uint16 rateBps;\n    }\n\n    /// @notice One bounded segment, its exact endpoint amounts and its termination information.\n    /// @dev amount equals cumulativeEnd minus cumulativeStart. An already completed period or\n    ///      exhausted cap returns end == start and amount == 0: the host must not open that marker\n    ///      in AccrualBook. Otherwise end is strictly later and at most 365 days away. complete\n    ///      means this period has no remaining entitlement after end; it does not retire the loan.\n    ///      capHit is meaningful only when capReachable, and may be zero for a zero grid cap.\n    struct Segment {\n        uint256 cumulativeStart;\n        uint256 cumulativeEnd;\n        uint256 amount;\n        uint64 start;\n        uint64 end;\n        uint64 capHit;\n        bool capReachable;\n        bool complete;\n    }\n\n    /// @notice A contractual period and its maturity must both lie after the original start.\n    error AccrualSegments_InvalidPeriod(uint64 periodStart, uint64 periodEnd, uint64 maturity);\n\n    /// @notice The requested timestamp lies outside this period's inclusive effective bounds.\n    error AccrualSegments_TimeOutsidePeriod(uint64 at, uint64 periodStart, uint64 effectiveEnd);\n\n    /// @notice Exact cumulative grid-rounded entitlement on the original frozen period basis.\n    /// @dev Computes floor(min(simpleInterest(at - periodStart), cap) / scale) * scale using\n    ///      AccrualMath's full-precision cap-before-grid calculation. This is the authoritative\n    ///      pure curve for early payoff, amendment and default reconciliation by the host; it\n    ///      must never be posted against a smaller book gross without matching reconciliation.\n    /// @param terms Fixed authenticated terms; existing AccrualMath numeric bounds apply.\n    /// @param at Inclusive timestamp from periodStart through min(periodEnd, maturity).\n    /// @return amount Total entitlement since periodStart, not a per-checkpoint increment.\n    function cumulative(Terms memory terms, uint64 at) internal pure returns (uint256 amount) {\n        uint64 effectiveEnd = _effectiveEnd(terms);\n        _validateTime(terms.periodStart, effectiveEnd, at);\n        amount = _cumulative(terms, at);\n    }\n\n    /// @notice Plans the next technical segment without modifying the contractual basis.\n    /// @dev Regular technical boundaries are anchored every 365 days to periodStart. A reachable\n    ///      cap inserts H-1 and H, where H is the first integer timestamp attaining the whole-grid\n    ///      cap. The final one-second segment prevents spreading the capped final increment over\n    ///      a long interval. No loop or precomputation proportional to period duration is needed.\n    /// @param terms Fixed terms, unchanged across technical successors.\n    /// @param technicalStart Requested start within the inclusive effective period bounds. The\n    ///      host must use the preceding endpoint except at an authorized lifecycle transition.\n    /// @return segment Exact cumulative endpoint difference and bounded scheduling metadata.\n    function plan(Terms memory terms, uint64 technicalStart) internal pure returns (Segment memory segment) {\n        uint64 effectiveEnd = _effectiveEnd(terms);\n        _validateTime(terms.periodStart, effectiveEnd, technicalStart);\n        segment.start = technicalStart;\n        segment.end = technicalStart;\n        segment.cumulativeStart = _cumulative(terms, technicalStart);\n        segment.cumulativeEnd = segment.cumulativeStart;\n\n        uint256 gridCap = terms.cap - terms.cap % terms.scale;\n        uint256 periodTotal = _cumulative(terms, effectiveEnd);\n        if (periodTotal == gridCap) {\n            segment.capReachable = true;\n            if (gridCap == 0) {\n                segment.capHit = terms.periodStart;\n            } else {\n                // Validation in _cumulative guarantees basis <= MAX/10_000 and rate <=10_000,\n                // so their product fits. A positive reachable grid cap proves a positive product.\n                // Reachability also proves the ceiling is <= effectiveEnd-periodStart (uint64).\n                uint256 elapsed =\n                    Math.mulDiv(gridCap, 10_000 * terms.yearSeconds, terms.basis * terms.rateBps, Math.Rounding.Ceil);\n                segment.capHit = terms.periodStart + uint64(elapsed);\n            }\n        }\n\n        if (technicalStart == effectiveEnd || (segment.capReachable && technicalStart >= segment.capHit)) {\n            segment.complete = true;\n            return segment;\n        }\n\n        uint64 remaining = effectiveEnd - technicalStart;\n        uint64 technicalRemaining = MAX_SEGMENT_SECONDS - (technicalStart - terms.periodStart) % MAX_SEGMENT_SECONDS;\n        segment.end = technicalStart + (remaining < technicalRemaining ? remaining : technicalRemaining);\n        if (segment.capReachable) {\n            uint64 capBoundary = segment.capHit;\n            if (capBoundary - technicalStart > 1) --capBoundary;\n            if (capBoundary < segment.end) segment.end = capBoundary;\n        }\n        segment.cumulativeEnd = _cumulative(terms, segment.end);\n        segment.amount = segment.cumulativeEnd - segment.cumulativeStart;\n        segment.complete = segment.end == effectiveEnd || (segment.capReachable && segment.end == segment.capHit);\n    }\n\n    /// @dev Validates positive contractual and maturity horizons without reading a clock.\n    function _effectiveEnd(Terms memory terms) private pure returns (uint64 effectiveEnd) {\n        if (terms.periodEnd <= terms.periodStart || terms.maturity <= terms.periodStart) {\n            revert AccrualSegments_InvalidPeriod(terms.periodStart, terms.periodEnd, terms.maturity);\n        }\n        effectiveEnd = terms.periodEnd < terms.maturity ? terms.periodEnd : terms.maturity;\n    }\n\n    /// @dev Inclusive bounds also permit querying the original start and exact final endpoint.\n    function _validateTime(uint64 periodStart, uint64 effectiveEnd, uint64 at) private pure {\n        if (at < periodStart || at > effectiveEnd) {\n            revert AccrualSegments_TimeOutsidePeriod(at, periodStart, effectiveEnd);\n        }\n    }\n\n    /// @dev Called only after validating time bounds; AccrualMath validates every numeric term.\n    function _cumulative(Terms memory terms, uint64 at) private pure returns (uint256) {\n        return AccrualMath.periodAmount(\n            terms.basis, terms.rateBps, at - terms.periodStart, terms.yearSeconds, terms.scale, terms.cap\n        );\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.20;\n\nimport {IAccessControl} from \"@openzeppelin/contracts/access/IAccessControl.sol\";\nimport {ContextUpgradeable} from \"../utils/ContextUpgradeable.sol\";\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {ERC165Upgradeable} from \"../utils/introspection/ERC165Upgradeable.sol\";\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```solidity\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```solidity\n * function foo() public {\n *     require(hasRole(MY_ROLE, msg.sender));\n *     ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}\n * to enforce additional security measures for this role.\n */\nabstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {\n    struct RoleData {\n        mapping(address account => bool) hasRole;\n        bytes32 adminRole;\n    }\n\n    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n\n    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl\n    struct AccessControlStorage {\n        mapping(bytes32 role => RoleData) _roles;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.AccessControl\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;\n\n    function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {\n        assembly {\n            $.slot := AccessControlStorageLocation\n        }\n    }\n\n    /**\n     * @dev Modifier that checks that an account has a specific role. Reverts\n     * with an {AccessControlUnauthorizedAccount} error including the required role.\n     */\n    modifier onlyRole(bytes32 role) {\n        _checkRole(role);\n        _;\n    }\n\n    function __AccessControl_init() internal onlyInitializing {\n    }\n\n    function __AccessControl_init_unchained() internal onlyInitializing {\n    }\n    /// @inheritdoc IERC165\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) public view virtual returns (bool) {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        return $._roles[role].hasRole[account];\n    }\n\n    /**\n     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`\n     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.\n     */\n    function _checkRole(bytes32 role) internal view virtual {\n        _checkRole(role, _msgSender());\n    }\n\n    /**\n     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`\n     * is missing `role`.\n     */\n    function _checkRole(bytes32 role, address account) internal view virtual {\n        if (!hasRole(role, account)) {\n            revert AccessControlUnauthorizedAccount(account, role);\n        }\n    }\n\n    /**\n     * @dev Returns the admin role that controls `role`. See {grantRole} and\n     * {revokeRole}.\n     *\n     * To change a role's admin, use {_setRoleAdmin}.\n     */\n    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        return $._roles[role].adminRole;\n    }\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     *\n     * May emit a {RoleGranted} event.\n     */\n    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {\n        _grantRole(role, account);\n    }\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * If `account` had been granted `role`, emits a {RoleRevoked} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {\n        _revokeRole(role, account);\n    }\n\n    /**\n     * @dev Revokes `role` from the calling account.\n     *\n     * Roles are often managed via {grantRole} and {revokeRole}: this function's\n     * purpose is to provide a mechanism for accounts to lose their privileges\n     * if they are compromised (such as when a trusted device is misplaced).\n     *\n     * If the calling account had been revoked `role`, emits a {RoleRevoked}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must be `callerConfirmation`.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function renounceRole(bytes32 role, address callerConfirmation) public virtual {\n        if (callerConfirmation != _msgSender()) {\n            revert AccessControlBadConfirmation();\n        }\n\n        _revokeRole(role, callerConfirmation);\n    }\n\n    /**\n     * @dev Sets `adminRole` as ``role``'s admin role.\n     *\n     * Emits a {RoleAdminChanged} event.\n     */\n    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        bytes32 previousAdminRole = getRoleAdmin(role);\n        $._roles[role].adminRole = adminRole;\n        emit RoleAdminChanged(role, previousAdminRole, adminRole);\n    }\n\n    /**\n     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.\n     *\n     * Internal function without access restriction.\n     *\n     * May emit a {RoleGranted} event.\n     */\n    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        if (!hasRole(role, account)) {\n            $._roles[role].hasRole[account] = true;\n            emit RoleGranted(role, account, _msgSender());\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.\n     *\n     * Internal function without access restriction.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        if (hasRole(role, account)) {\n            $._roles[role].hasRole[account] = false;\n            emit RoleRevoked(role, account, _msgSender());\n            return true;\n        } else {\n            return false;\n        }\n    }\n}\n"},{"file_path":"src/libraries/ReserveMigrationLib.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {IAccessControl} from \"@openzeppelin/contracts/access/IAccessControl.sol\";\nimport {ClaimBridge} from \"../ClaimBridge.sol\";\nimport {ReserveManager as Native} from \"../ReserveManager.sol\";\nimport {IAttestationOracle} from \"../interfaces/IAttestationOracle.sol\";\nimport {ICollateralRegistry} from \"../interfaces/ICollateralRegistry.sol\";\nimport {IContinuousAccrual} from \"../interfaces/IContinuousAccrual.sol\";\nimport {IAccrualRegistry, IAccrualBridge} from \"../interfaces/IAccrualLifecycle.sol\";\nimport {IAccrualMigration, IAccrualMigrationRisk} from \"../interfaces/IAccrualMigration.sol\";\nimport {IWaterfallEngine} from \"../interfaces/IWaterfallEngine.sol\";\nimport {IsUSDfr} from \"../interfaces/IsUSDfr.sol\";\nimport {AccrualBook} from \"./AccrualBook.sol\";\nimport {AccrualLoans} from \"./AccrualLoans.sol\";\nimport {AccrualCeiling} from \"./AccrualCeiling.sol\";\nimport {AccrualMath} from \"./AccrualMath.sol\";\nimport {Config} from \"./Config.sol\";\nimport {Roles} from \"./Roles.sol\";\nimport {ReserveAccrualLib} from \"./ReserveAccrualLib.sol\";\nimport {ReserveAccrualStorageLib} from \"./ReserveAccrualStorageLib.sol\";\nimport {ReserveStorageLib} from \"./ReserveStorageLib.sol\";\n\n/// @notice Governed, bounded import of existing receivables without exposing a partial senior NAV.\n/// @dev The host retains its admin and reentrancy guards. A complete sorted positive-face roster\n///      is frozen before signatures are collected. Each row's native record, session and complete\n///      opening are authenticated before its face and risk are increased. No tokens move on import.\nlibrary ReserveMigrationLib {\n    using AccrualBook for AccrualBook.Book;\n    using AccrualLoans for AccrualLoans.State;\n\n    uint256 internal constant MAX_BATCH = 8;\n    bytes32 internal constant OPENING_TYPEHASH = keccak256(\"AccrualOpening(bytes32 frozenRecord,bytes32 opening)\");\n\n    struct Row {\n        ClaimBridge.Facility facility;\n        address asset;\n        uint256 scale;\n        uint256 recorded;\n        bytes32 commitment;\n    }\n\n    error AccrualMigration_InvalidAction(uint8 action);\n    error AccrualMigration_InvalidRoster();\n    error AccrualMigration_InvalidFacility(uint256 facilityId);\n    error AccrualMigration_UnsupportedTerms(uint256 facilityId);\n    error AccrualMigration_AlreadyStarted();\n    error AccrualMigration_NotStarted();\n    error AccrualMigration_InvalidBatch();\n    error AccrualMigration_RecordChanged(uint256 facilityId);\n    error AccrualMigration_AttestationRequired(uint256 facilityId);\n    error AccrualMigration_OracleNotReady(address oracle);\n    error AccrualMigration_CannotCancelImportedDebt();\n    error AccrualMigration_ExposureCapacity();\n    error AccrualMigration_InexactOpening(uint256 facilityId);\n    error AccrualMigration_NonceOverflow();\n\n    /// @notice All native servicing is frozen at cutoff against this complete roster commitment.\n    event AccrualMigrationBegun(\n        uint256 indexed nonce, bytes32 indexed sessionKey, uint64 cutoff, uint32 expected, uint256 originalFace\n    );\n    /// @notice The opening was consumed once, posted to deployed face and reconciled into native risk.\n    event AccrualOpeningImported(\n        uint256 indexed nonce,\n        uint256 indexed facilityId,\n        uint256 recordedBefore,\n        uint256 principal,\n        uint256 interest,\n        uint256 income,\n        bool permanentlyStopped,\n        bool pastDue\n    );\n    /// @notice A session with no imported debt was cancelled; its nonce can never be reused.\n    event AccrualMigrationCancelled(uint256 indexed nonce, bytes32 indexed sessionKey);\n\n    /// @notice Decodes one explicitly authorized preparation step; every failed batch is atomic.\n    function prepare(Native.ReserveStorage storage native, bytes calldata step) public {\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        if (s.busy || s.delivery.active) revert ReserveAccrualLib.ReserveAccrual_OperationInProgress();\n        if (s.enabled) revert ReserveAccrualLib.ReserveAccrual_AlreadyConfigured();\n        (uint8 action, bytes memory body) = abi.decode(step, (uint8, bytes));\n        if (action == 0) {\n            _begin(native, s, abi.decode(body, (uint256[])));\n        } else if (action == 1) {\n            _import(native, s, abi.decode(body, (IAccrualMigration.Opening[])));\n        } else if (action == 2) {\n            if (body.length != 0) revert AccrualMigration_InvalidBatch();\n            _cancel(s);\n        } else {\n            revert AccrualMigration_InvalidAction(action);\n        }\n    }\n\n    function _begin(\n        Native.ReserveStorage storage native,\n        ReserveAccrualStorageLib.State storage s,\n        uint256[] memory ids\n    ) private {\n        if (s.migration.active) revert AccrualMigration_AlreadyStarted();\n        if (ids.length == 0 || ids.length > AccrualBook.MAX_FACILITIES) revert AccrualMigration_InvalidRoster();\n        IContinuousAccrual.Modules memory modules_ = s.modules;\n        ReserveAccrualLib.requireConsumers(modules_);\n        _oracle(modules_.bridge);\n        uint16 feeBps = IWaterfallEngine(modules_.waterfall).protocolFeeBps();\n        if (feeBps > Config.MAX_PROTOCOL_FEE_BPS) revert ReserveAccrualLib.ReserveAccrual_InvalidFee(feeBps);\n        address recipient = IWaterfallEngine(modules_.waterfall).feeRecipient();\n        if (recipient == address(0)) revert ReserveAccrualLib.ReserveAccrual_WrongModules();\n        // Close the pre-migration fee epoch before hiding preparation from financial entry points.\n        IsUSDfr(modules_.vault).accrueFees();\n        ReserveAccrualStorageLib.Migration storage m = s.migration;\n        if (m.nonce == type(uint256).max) revert AccrualMigration_NonceOverflow();\n        ++m.nonce;\n        m.cutoff = ReserveAccrualStorageLib.now64();\n        m.expected = uint32(ids.length);\n        m.feeBps = feeBps;\n        s.feeRecipient = recipient;\n        m.sessionKey = keccak256(\n            abi.encode(\n                block.chainid, address(this), m.nonce, m.cutoff, keccak256(abi.encode(ids)), modules_, feeBps, recipient\n            )\n        );\n        m.active = true;\n        uint256 total;\n        uint256 work;\n        for (uint256 i; i < ids.length; ++i) {\n            uint256 id = ids[i];\n            if (id == 0 || (i != 0 && id <= ids[i - 1])) revert AccrualMigration_InvalidRoster();\n            Row memory row = _row(native, s, id);\n            total += row.recorded;\n            if (!_stopped(row.facility) && row.facility.maturity > m.cutoff && row.facility.interestRateBps != 0) {\n                uint256 interval = row.facility.paymentInterval;\n                work += row.facility.pik\n                    ? AccrualLoans.YEAR / interval + (AccrualLoans.YEAR % interval == 0 ? 0 : 1) + 4\n                    : 4;\n            }\n            m.facilityIds.push(id);\n            m.frozenRecords[id] = row.commitment;\n        }\n        if (total != native.totalDeployedPrincipal) revert AccrualMigration_InvalidRoster();\n        if (work > AccrualLoans.MAX_ANNUAL_WORK) revert AccrualLoans.AccrualLoans_WorkCapacity(work);\n        m.originalFace = total;\n        emit AccrualMigrationBegun(m.nonce, m.sessionKey, m.cutoff, m.expected, total);\n    }\n\n    function _import(\n        Native.ReserveStorage storage native,\n        ReserveAccrualStorageLib.State storage s,\n        IAccrualMigration.Opening[] memory openings\n    ) private {\n        ReserveAccrualStorageLib.Migration storage m = s.migration;\n        if (!m.active) revert AccrualMigration_NotStarted();\n        if (openings.length == 0 || openings.length > MAX_BATCH || openings.length > m.expected - m.imported) {\n            revert AccrualMigration_InvalidBatch();\n        }\n        if (m.imported == 0) s.loans.initialize(m.cutoff, m.feeBps);\n        IAttestationOracle oracle = _oracle(s.modules.bridge);\n        s.busy = true;\n        for (uint256 i; i < openings.length; ++i) {\n            IAccrualMigration.Opening memory opening = openings[i];\n            uint256 id = opening.facilityId;\n            if (id != m.facilityIds[m.imported] || s.identities[id].known) revert AccrualMigration_InvalidBatch();\n            Row memory row = _row(native, s, id);\n            if (row.commitment != m.frozenRecords[id]) revert AccrualMigration_RecordChanged(id);\n            _consume(oracle, m.cutoff, row.commitment, opening);\n            _importRow(native, s, row, opening);\n            m.importedOriginalFace += row.recorded;\n            ++m.imported;\n        }\n        s.busy = false;\n    }\n\n    function _importRow(\n        Native.ReserveStorage storage native,\n        ReserveAccrualStorageLib.State storage s,\n        Row memory row,\n        IAccrualMigration.Opening memory opening\n    ) private {\n        uint256 id = opening.facilityId;\n        AccrualLoans.Opening memory imported = _loan(row, opening, s.migration.cutoff);\n        uint256 ceiling = imported.terms.balanceCeiling;\n        uint256 effective = ICollateralRegistry(s.modules.registry).totalBookExposure();\n        uint256 reserved = s.reservedCeilings - s.recordedFace;\n        uint256 extra = ceiling - row.recorded;\n        if (\n            effective > AccrualLoans.MAX_BASIS || reserved > AccrualLoans.MAX_BASIS - effective\n                || extra > AccrualLoans.MAX_BASIS - effective - reserved\n        ) revert AccrualMigration_ExposureCapacity();\n        uint256 income = s.loans.importOpening(id, imported);\n        uint256 posting = s.loans.book.takePosting(id, s.migration.cutoff);\n        assert(posting == income);\n        s.identities[id] = ReserveAccrualStorageLib.Identity({\n            asset: row.asset,\n            classId: row.facility.classId,\n            borrowerId: row.facility.borrowerId,\n            stateId: row.facility.stateId,\n            reservedCeiling: ceiling,\n            known: true\n        });\n        native.deployed[id] += income;\n        native.totalDeployedPrincipal += income;\n        s.recordedFace += row.recorded + income;\n        s.reservedCeilings += ceiling;\n        if (income != 0) {\n            IAccrualRegistry(s.modules.registry).recordAccruedExposure(\n                row.facility.classId, row.facility.borrowerId, row.facility.stateId, income\n            );\n        }\n        // Importing completed historical coupons must also advance the native servicing date.\n        // The attested opening supplies the coupon; an already later servicing date stays in place.\n        if (\n            row.facility.pik && !imported.permanentlyStopped && opening.nextCapitalization > row.facility.nextPaymentDue\n        ) {\n            IAccrualBridge(s.modules.bridge).setAccruedPaymentDue(id, opening.nextCapitalization);\n        }\n        bool marked = IAccrualMigrationRisk(s.modules.defaultManager).onAccrualOpening(id, income);\n        if (marked) s.loans.book.setPastDue(id, true, s.migration.cutoff);\n        emit AccrualOpeningImported(\n            s.migration.nonce,\n            id,\n            row.recorded,\n            opening.principal,\n            opening.interest,\n            income,\n            imported.permanentlyStopped,\n            marked\n        );\n    }\n\n    function _loan(Row memory row, IAccrualMigration.Opening memory opening, uint64 cutoff)\n        private\n        pure\n        returns (AccrualLoans.Opening memory result)\n    {\n        ClaimBridge.Facility memory f = row.facility;\n        uint256 id = opening.facilityId;\n        if (\n            opening.principal % row.scale != 0 || opening.interest % row.scale != 0\n                || opening.frozenPikBasis % row.scale != 0\n        ) revert AccrualMigration_InexactOpening(id);\n        if (!f.pik && (opening.principal > row.recorded || opening.nextCapitalization != 0)) {\n            revert AccrualMigration_InvalidFacility(id);\n        }\n        if (opening.principal > AccrualLoans.MAX_BASIS || opening.interest > AccrualLoans.MAX_BASIS - opening.principal)\n        {\n            revert AccrualMigration_ExposureCapacity();\n        }\n        uint256 face = opening.principal + opening.interest;\n        if (face < row.recorded || opening.periodStart > cutoff || opening.periodStart >= f.maturity) {\n            revert AccrualMigration_InvalidFacility(id);\n        }\n        uint32 yearSeconds = _year(f, id);\n        uint256 ceiling = face;\n        bool stopped = _stopped(f);\n        if (!stopped && cutoff < f.maturity) {\n            if (f.pik) {\n                // The quorum authenticates the pending coupon and its frozen epoch. Legacy\n                // receipts can advance the bridge's servicing date independently of that coupon.\n                ceiling = AccrualCeiling.pik(\n                    AccrualCeiling.Terms({\n                        face: face,\n                        frozenBasis: opening.frozenPikBasis == 0 ? opening.principal : opening.frozenPikBasis,\n                        scale: row.scale,\n                        yearSeconds: yearSeconds,\n                        rateBps: f.interestRateBps,\n                        at: cutoff,\n                        nextCapitalization: opening.nextCapitalization,\n                        paymentInterval: f.paymentInterval,\n                        maturity: f.maturity\n                    })\n                );\n            } else {\n                uint256 end = AccrualMath.earnedInterest(\n                    opening.principal, f.interestRateBps, f.maturity - opening.periodStart, yearSeconds\n                ) / row.scale;\n                uint256 previous = AccrualMath.earnedInterest(\n                    opening.principal, f.interestRateBps, cutoff - opening.periodStart, yearSeconds\n                ) / row.scale;\n                uint256 remaining = (end - previous) * row.scale;\n                if (remaining > AccrualLoans.MAX_BASIS - face) revert AccrualMigration_ExposureCapacity();\n                ceiling += remaining;\n            }\n        }\n        result = AccrualLoans.Opening({\n            terms: AccrualLoans.Funding({\n                principal: opening.principal,\n                balanceCeiling: ceiling,\n                scale: row.scale,\n                yearSeconds: yearSeconds,\n                rateBps: f.interestRateBps,\n                fundedAt: cutoff,\n                nextPaymentDue: f.pik ? opening.nextCapitalization : f.nextPaymentDue,\n                paymentInterval: f.paymentInterval,\n                maturity: f.maturity,\n                pik: f.pik,\n                keys: ReserveAccrualStorageLib.keys(f.classId, f.borrowerId, f.stateId),\n                frozenPikBasis: opening.frozenPikBasis\n            }),\n            recordedFace: row.recorded,\n            interest: opening.interest,\n            periodStart: opening.periodStart,\n            permanentlyStopped: stopped\n        });\n    }\n\n    function _row(Native.ReserveStorage storage native, ReserveAccrualStorageLib.State storage s, uint256 id)\n        private\n        view\n        returns (Row memory row)\n    {\n        row.facility = ClaimBridge(s.modules.bridge).facility(id);\n        row.recorded = native.deployed[id];\n        (row.asset, row.scale) = _asset(native, id);\n        ClaimBridge.Facility memory f = row.facility;\n        if (\n            row.recorded == 0 || row.recorded > AccrualLoans.MAX_BASIS || row.asset.code.length == 0 || f.principal == 0\n                || f.paymentInterval == 0 || f.maturity == 0 || f.nextPaymentDue == 0 || f.nextPaymentDue > f.maturity\n                || (f.state != ClaimBridge.LoanState.Active && f.state != ClaimBridge.LoanState.Amortizing && !_stopped(f))\n        ) revert AccrualMigration_InvalidFacility(id);\n        _year(f, id);\n        ICollateralRegistry(s.modules.registry).classParams(f.classId);\n        row.commitment =\n            keccak256(abi.encode(s.migration.sessionKey, id, row.asset, row.recorded, keccak256(abi.encode(f))));\n    }\n\n    function _asset(Native.ReserveStorage storage native, uint256) private view returns (address, uint256) {\n        return (address(native.usdcToken), ReserveStorageLib.USDC_SCALE);\n    }\n\n    function _year(ClaimBridge.Facility memory f, uint256 id) private pure returns (uint32) {\n        if (f.rateType != ClaimBridge.RateType.Fixed || f.interestRateBps > 10_000) {\n            revert AccrualMigration_UnsupportedTerms(id);\n        }\n        if (f.dayCountConvention == ClaimBridge.DayCountConvention.Actual360) return uint32(360 days);\n        if (!f.pik && f.dayCountConvention == ClaimBridge.DayCountConvention.Actual365) return uint32(365 days);\n        revert AccrualMigration_UnsupportedTerms(id);\n    }\n\n    function _stopped(ClaimBridge.Facility memory f) private pure returns (bool) {\n        return f.state == ClaimBridge.LoanState.Defaulted || f.state == ClaimBridge.LoanState.Accelerated;\n    }\n\n    function _oracle(address bridge) private view returns (IAttestationOracle oracle) {\n        (, address target) = ClaimBridge(bridge).modules();\n        oracle = IAttestationOracle(target);\n        if (\n            target.code.length == 0 || oracle.threshold(IAttestationOracle.AttestationKind.AccrualOpening) < 2\n                || !IAccessControl(target).hasRole(Roles.CREDIT_ROLE, address(this))\n        ) {\n            revert AccrualMigration_OracleNotReady(target);\n        }\n    }\n\n    function _consume(\n        IAttestationOracle oracle,\n        uint64 cutoff,\n        bytes32 record,\n        IAccrualMigration.Opening memory opening\n    ) private {\n        bytes32 expected = keccak256(abi.encode(OPENING_TYPEHASH, record, keccak256(abi.encode(opening))));\n        (bytes32 payload, uint64 asOf, bool satisfied) =\n            oracle.latestPayload(opening.facilityId, IAttestationOracle.AttestationKind.AccrualOpening);\n        if (!satisfied || asOf != cutoff || payload != expected) {\n            revert AccrualMigration_AttestationRequired(opening.facilityId);\n        }\n        oracle.consume(opening.facilityId, IAttestationOracle.AttestationKind.AccrualOpening);\n    }\n\n    function _cancel(ReserveAccrualStorageLib.State storage s) private {\n        ReserveAccrualStorageLib.Migration storage m = s.migration;\n        if (!m.active) revert AccrualMigration_NotStarted();\n        if (m.imported != 0) revert AccrualMigration_CannotCancelImportedDebt();\n        emit AccrualMigrationCancelled(m.nonce, m.sessionKey);\n        m.active = false;\n        m.cutoff = 0;\n        m.expected = 0;\n        m.feeBps = 0;\n        m.originalFace = 0;\n        m.sessionKey = bytes32(0);\n        delete m.facilityIds;\n        s.feeRecipient = address(0);\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol","source_code":"// 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"},{"file_path":"src/libraries/ReserveWiringLib.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IERC4626} from \"@openzeppelin/contracts/interfaces/IERC4626.sol\";\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {ReserveManager} from \"../ReserveManager.sol\";\nimport {IReserveManager} from \"../interfaces/IReserveManager.sol\";\nimport {IReserveLossAbsorber} from \"../interfaces/IReserveLossAbsorber.sol\";\nimport {IMintRedeemController} from \"../interfaces/IMintRedeemController.sol\";\nimport {ICuratorModule} from \"../interfaces/ICuratorModule.sol\";\nimport {ICascadeBackstop} from \"../interfaces/ICascadeBackstop.sol\";\nimport {IsUSDfr} from \"../interfaces/IsUSDfr.sol\";\nimport {IReserveLossGovernor, IReserveLossTimelock} from \"../interfaces/IReserveLossGovernance.sol\";\nimport {ReserveAccrualStorageLib} from \"./ReserveAccrualStorageLib.sol\";\nimport {ReserveAccrualLib} from \"./ReserveAccrualLib.sol\";\n/// @notice Native Ethereum module binding with the unchanged reserve storage pointer.\n/// @dev The host retains roles and callback exclusion. Continuous configuration freezes all routes.\n\nlibrary ReserveWiringLib {\n    /// @notice Binds native counterparties under the host's existing governance authority.\n    function bindAbsorber(ReserveManager.ReserveStorage storage $, address absorber) public {\n        _requireModuleRebindAllowed($);\n        (bool readable, address source) = _readStaticAddress(absorber, IReserveLossAbsorber.reserveLossSource.selector);\n        if (!readable || source != address(this)) {\n            revert IReserveManager.ReserveManager_InvalidLossAbsorber(absorber);\n        }\n        address previous = address($.lossAbsorber);\n        $.lossAbsorber = IReserveLossAbsorber(absorber);\n        emit IReserveManager.LossAbsorberSet(previous, absorber);\n    }\n\n    /// @notice Binds native counterparties under the host's existing governance authority.\n    function bindController(ReserveManager.ReserveStorage storage $, address controller_) public {\n        _requireModuleRebindAllowed($);\n        if (controller_ == address(0) || controller_.code.length == 0) {\n            revert IReserveManager.ReserveManager_InvalidLossController(controller_);\n        }\n        address boundReserves;\n        address usdfr_;\n        try IMintRedeemController(controller_).modules() returns (address usdfr__, address, address reserves_) {\n            usdfr_ = usdfr__;\n            boundReserves = reserves_;\n        } catch {\n            revert IReserveManager.ReserveManager_InvalidLossController(controller_);\n        }\n        if (boundReserves != address(this) || usdfr_ == address(0) || usdfr_.code.length == 0) {\n            revert IReserveManager.ReserveManager_InvalidLossController(controller_);\n        }\n        address previous = address($.lossController);\n        $.lossController = IMintRedeemController(controller_);\n        $.lossUSDfr = IERC20(usdfr_);\n        emit IReserveManager.LossControllerSet(previous, controller_);\n    }\n\n    /// @notice Binds native counterparties under the host's existing governance authority.\n    function bindModules(\n        ReserveManager.ReserveStorage storage $,\n        address curator,\n        address backstop,\n        address vault,\n        address governor,\n        address timelock\n    ) public {\n        _requireModuleRebindAllowed($);\n        if (address($.lossController) == address(0)) {\n            revert IReserveManager.ReserveManager_InvalidLossController(address(0));\n        }\n        if (curator == address(0) || curator.code.length == 0) {\n            revert IReserveManager.ReserveManager_InvalidLossAbsorber(curator);\n        }\n        if (backstop == address(0) || backstop.code.length == 0) {\n            revert IReserveManager.ReserveManager_InvalidLossAbsorber(backstop);\n        }\n        if (vault == address(0) || vault.code.length == 0) {\n            revert IReserveManager.ReserveManager_InvalidLossAbsorber(vault);\n        }\n\n        {\n            address curatorUSDfr;\n            address curatorVault;\n            try ICuratorModule(curator).modules() returns (address usdfr_, address, address vault_) {\n                curatorUSDfr = usdfr_;\n                curatorVault = vault_;\n            } catch {\n                revert IReserveManager.ReserveManager_InvalidLossAbsorber(curator);\n            }\n            (bool curatorReserveReadable, address curatorReserve) =\n                _readStaticAddress(curator, ICuratorModule.reserveManager.selector);\n            if (!curatorReserveReadable) revert IReserveManager.ReserveManager_InvalidLossAbsorber(curator);\n            (bool vaultAssetReadable, address vaultAsset) = _readStaticAddress(vault, IERC4626.asset.selector);\n            if (!vaultAssetReadable) revert IReserveManager.ReserveManager_InvalidLossAbsorber(vault);\n            if (\n                curatorUSDfr != address($.lossUSDfr) || curatorVault != vault || curatorReserve != address(this)\n                    || vaultAsset != address($.lossUSDfr)\n            ) revert IReserveManager.ReserveManager_InvalidLossAbsorber(curator);\n        }\n        {\n            bool supported;\n            try IERC165(backstop).supportsInterface(type(ICascadeBackstop).interfaceId) returns (bool ok) {\n                supported = ok;\n            } catch {\n                supported = false;\n            }\n            if (!supported) revert IReserveManager.ReserveManager_InvalidLossAbsorber(backstop);\n        }\n\n        if (!_governanceTimingValid(governor, timelock)) {\n            revert IReserveManager.ReserveManager_InvalidGovernanceTiming(governor, timelock);\n        }\n        $.lossCurator = ICuratorModule(curator);\n        $.lossBackstop = ICascadeBackstop(backstop);\n        $.lossVault = IsUSDfr(vault);\n        $.lossGovernor = governor;\n        $.lossTimelock = timelock;\n        emit IReserveManager.ReserveLossModulesSet(curator, backstop, vault, governor, timelock);\n    }\n\n    function _requireModuleRebindAllowed(ReserveManager.ReserveStorage storage $) private view {\n        if (ReserveAccrualStorageLib.state().modules.token != address(0)) {\n            revert ReserveAccrualLib.ReserveAccrual_AlreadyConfigured();\n        }\n        if (\n            $.activeReserveLossArmId != 0 || $.activeReserveLossIncidentId != 0 || $.recognizedSupplyReduction != 0\n                || $.reserveDeficit != 0 || _liveShortfallUnits($) != 0\n        ) revert IReserveManager.ReserveManager_ModuleRebindForbidden();\n        IMintRedeemController controller = $.lossController;\n        if (address(controller) != address(0) && controller.totalUSDfr() > controller.backingValue()) {\n            revert IReserveManager.ReserveManager_ModuleRebindForbidden();\n        }\n    }\n\n    function _governanceTimingValid(address governor, address timelock) private view returns (bool) {\n        (bool ok, uint256 word) = _readStaticWord(governor, IReserveLossGovernor.timelock.selector);\n        if (!ok || address(uint160(word)) != timelock) return false;\n        (ok, word) = _readStaticWord(governor, IReserveLossGovernor.clock.selector);\n        if (!ok || word != block.timestamp) return false;\n\n        (bool modeOk, bytes memory modeData) =\n            governor.staticcall(abi.encodeWithSelector(IReserveLossGovernor.CLOCK_MODE.selector));\n        if (!modeOk || keccak256(modeData) != keccak256(abi.encode(\"mode=timestamp\"))) return false;\n\n        (ok,) = _readStaticWord(governor, IReserveLossGovernor.votingDelay.selector);\n        if (!ok) return false;\n        (ok,) = _readStaticWord(governor, IReserveLossGovernor.votingPeriod.selector);\n        if (!ok) return false;\n        (ok,) = _readStaticWord(timelock, IReserveLossTimelock.getMinDelay.selector);\n        return ok;\n    }\n\n    function _readStaticWord(address target, bytes4 selector) private view returns (bool ok, uint256 word) {\n        if (target == address(0) || target.code.length == 0) return (false, 0);\n        bytes memory data;\n        (ok, data) = target.staticcall(abi.encodeWithSelector(selector));\n        if (!ok || data.length < 32) return (false, 0);\n        assembly (\"memory-safe\") {\n            word := mload(add(data, 0x20))\n        }\n    }\n\n    function _readStaticAddress(address target, bytes4 selector) private view returns (bool ok, address value) {\n        uint256 word;\n        (ok, word) = _readStaticWord(target, selector);\n        if (!ok || word > type(uint160).max) return (false, address(0));\n        value = address(uint160(word));\n    }\n\n    function _liveShortfallUnits(ReserveManager.ReserveStorage storage $) private view returns (uint256) {\n        uint256 live = $.usdcToken.balanceOf(address(this));\n        return $.idleUSDCUnits > live ? $.idleUSDCUnits - live : 0;\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {Initializable} from \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165 {\n    function __ERC165_init() internal onlyInitializing {\n    }\n\n    function __ERC165_init_unchained() internal onlyInitializing {\n    }\n    /// @inheritdoc IERC165\n    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {\n        return interfaceId == type(IERC165).interfaceId;\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol","source_code":"// 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 \"../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"},{"file_path":"lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Metadata.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC721} from \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n    /**\n     * @dev Returns the token collection name.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the token collection symbol.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n     */\n    function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"},{"file_path":"src/interfaces/IComplianceRegistry.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\n/// @title IComplianceRegistry\n/// @notice Compliance capability layer (ADR-0011, as amended by the 2026-07-14 directive):\n///         a KYC allowlist consulted ONLY at the mint/redeem primary gate, and a narrow\n///         sanctions blocklist consulted on transfers. The per-token transfer-allowlist\n///         capability was removed — transfers are permissionless (sanctions-only). Policy\n///         (who is eligible/sanctioned) is set by governance/counsel off this interface.\ninterface IComplianceRegistry {\n    /// @notice Emitted when an account's KYC allowlist status changes.\n    event AllowlistUpdated(address indexed account, bool allowed);\n    /// @notice Emitted when an account's sanctions/jurisdiction-block status changes.\n    event JurisdictionBlockUpdated(address indexed account, bool blocked);\n    /// @notice Timelocked governance changed an address's borrower-payout approval.\n    /// @dev This list is deliberately independent of the operational KYC allowlist.\n    event FundingRecipientApprovalUpdated(address indexed account, bool approved);\n\n    /// @notice True if `account` has passed KYC and may use the gated primary paths\n    ///         (USDfr mint/redeem). Holding and transferring are permissionless.\n    function isAllowed(address account) external view returns (bool);\n\n    /// @notice True if `account` is on the sanctions/jurisdiction blocklist.\n    function isJurisdictionBlocked(address account) external view returns (bool);\n\n    /// @notice True only when timelocked governance approved `account` as a borrower-payout\n    ///         destination and the account is not currently jurisdiction-blocked.\n    function isFundingRecipientAllowed(address account) external view returns (bool);\n\n    /// @notice True for a governance-designated internal protocol module.\n    function isProtocolExempt(address module) external view returns (bool);\n\n    /// @notice Transfer gate consulted by protocol tokens on every transfer. Transfers are\n    ///         permissionless except for sanctioned (blocked) parties; burns are always\n    ///         permitted; protocol modules are never treated as blocked.\n    /// @param token Retained for interface stability; no longer affects the result.\n    /// @param from Sender (zero on mint).\n    /// @param to Recipient (zero on burn).\n    /// @return True if the transfer may proceed.\n    function canTransfer(address token, address from, address to) external view returns (bool);\n}\n"},{"file_path":"src/libraries/Roles.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\n// GENERATED by tools/generate-privilege-topology.mjs from config/privilege-topology.json.\n// Do not edit this file directly; the compiler-AST topology gate rejects drift.\n\n/// @title Roles\n/// @notice Canonical role identifiers for the protocol's access-control matrix.\n/// @dev DEFAULT_ADMIN_ROLE is inherited from AccessControl and represented by bytes32(0).\nlibrary Roles {\n    // NOTE: A QUEUE_ROLE existed through Phase H but was never consumed. The vault gates its exit by the configured redemption-queue address, which is the stronger check; it was removed at Phase I cleanup.\n\n    /// @notice May authorize UUPS upgrades. Held only by the governance timelock.\n    bytes32 internal constant UPGRADER_ROLE = keccak256(\"UPGRADER_ROLE\");\n\n    /// @notice Emergency pause/unpause on value-moving paths. Cannot upgrade or move value.\n    bytes32 internal constant GUARDIAN_ROLE = keccak256(\"GUARDIAN_ROLE\");\n\n    /// @notice May mint USDfr. Held only by the MintRedeemController.\n    bytes32 internal constant MINTER_ROLE = keccak256(\"MINTER_ROLE\");\n\n    /// @notice Reserve custody operations (deposit/release). Held only by the MintRedeemController.\n    bytes32 internal constant CONTROLLER_ROLE = keccak256(\"CONTROLLER_ROLE\");\n\n    /// @notice Principal deployment, atomic payment receipt, and writedown. Held by credit modules.\n    bytes32 internal constant CREDIT_ROLE = keccak256(\"CREDIT_ROLE\");\n\n    /// @notice May burn USDfr to realize an authenticated loss. Held only by DefaultManager and ReserveManager.\n    /// @dev AUDIT R16-M1: burnLoss is deliberately split from CREDIT_ROLE so the repayment engine cannot compose mint and burn authority.\n    bytes32 internal constant LOSS_BURNER_ROLE = keccak256(\"LOSS_BURNER_ROLE\");\n\n    /// @notice May bracket a junior-capacity change so the vault preserves its asset-denominated performance-fee hurdle. Held only by the curator, sGROVE, and DefaultManager modules.\n    bytes32 internal constant FEE_ACCOUNTING_ROLE = keccak256(\"FEE_ACCOUNTING_ROLE\");\n\n    /// @notice Manages KYC allowlist and jurisdiction blocklist entries.\n    bytes32 internal constant COMPLIANCE_ADMIN_ROLE = keccak256(\"COMPLIANCE_ADMIN_ROLE\");\n\n    /// @notice Reserve configuration and conservative USDC custody write-downs.\n    bytes32 internal constant RESERVE_ADMIN_ROLE = keccak256(\"RESERVE_ADMIN_ROLE\");\n\n    /// @notice May originate facilities (Phase D).\n    bytes32 internal constant ORIGINATOR_ROLE = keccak256(\"ORIGINATOR_ROLE\");\n\n    /// @notice Authorized attesters (Phase G, ADR-0007).\n    bytes32 internal constant ATTESTER_ROLE = keccak256(\"ATTESTER_ROLE\");\n\n    /// @notice Servicing operations: facility funding, repayment distribution, default declaration, and loss realization. Held by Forest Road servicing keys until Phase G binds these paths to attested facts; the role then gates who may execute an already-attested action, not what is true.\n    bytes32 internal constant SERVICER_ROLE = keccak256(\"SERVICER_ROLE\");\n\n    /// @notice Drives RedemptionQueue.closeEpoch. Operational, not governance or upgrade authority: it initiates a financially effective settlement and controls when its budget is sampled, but cannot choose recipients, reorder FIFO, set parameters, or exceed the contract-enforced budget and pricing rules.\n    /// @dev AUDIT FIX D7-01: closeEpoch samples the epoch liquidity budget as a spot read and the fill loop re-reads it every chunk. While permissionless, a caller could hold flash liquidity across both reads; measured excess budget was $1.62M from Morpho alone and $4.31M from stacked Aave and Morpho borrowing. A flash loan cannot span two transactions, so the keeper gate closes the vector at its root. This supersedes ADR-0018 section 2's permissionless-settlement design. Grant the role to at least two holders: a hot keeper and a manual ops-multisig backstop. A total keeper outage is bounded only by governance regranting the role. A permissionless grace fallback was rejected because it would restore the flash vector whenever the keeper missed the window.\n    bytes32 internal constant SETTLEMENT_KEEPER_ROLE = keccak256(\"SETTLEMENT_KEEPER_ROLE\");\n}\n"},{"file_path":"src/libraries/LossEventIds.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\n/// @title LossEventIds — disjoint namespaces for facility and custody-loss events\n/// @notice Facility NFTs use the lower half of uint256. Governance-assigned custody incidents\n///         use the upper half, so both kinds can safely share SGrove's event-coverage mappings.\nlibrary LossEventIds {\n    uint256 internal constant CUSTODY_EVENT_NAMESPACE_START = 1 << 255;\n\n    error LossEventIds_InvalidCustodyArm(uint256 armId);\n\n    function isFacilityEvent(uint256 eventId) internal pure returns (bool) {\n        return eventId < CUSTODY_EVENT_NAMESPACE_START;\n    }\n\n    function isCustodyEvent(uint256 eventId) internal pure returns (bool) {\n        return eventId >= CUSTODY_EVENT_NAMESPACE_START;\n    }\n\n    /// @dev Arm ids are generated internally, start at one and stay in the lower namespace.\n    ///      The explicit post-condition keeps the facility/custody partition executable rather\n    ///      than relying on a comment at each call site.\n    function custodyEventId(uint256 armId) internal pure returns (uint256 eventId) {\n        if (armId == 0 || armId >= CUSTODY_EVENT_NAMESPACE_START) {\n            revert LossEventIds_InvalidCustodyArm(armId);\n        }\n        eventId = type(uint256).max - armId;\n        assert(eventId >= CUSTODY_EVENT_NAMESPACE_START);\n    }\n}\n"},{"file_path":"src/interfaces/IsUSDfr.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {IERC4626} from \"@openzeppelin/contracts/interfaces/IERC4626.sol\";\n\n/// @title IsUSDfr\n/// @notice The yield-bearing ERC-4626 vault over USDfr (ADR-0005). Yield accrues via the\n///         assets/shares exchange rate; exits are routed through the epoch redemption\n///         queue (ADR-0010) — the vault's instant withdraw/redeem paths are restricted\n///         to the queue module.\ninterface IsUSDfr is IERC4626 {\n    /// @notice Emitted when the redemption queue address is set.\n    event RedemptionQueueUpdated(address indexed queue);\n\n    /// @notice Instant exit attempted by an account other than the redemption queue.\n    error SUSDfr_QueueOnly();\n    /// @notice Share movement involving a sanctioned (blocked) party.\n    error SUSDfr_TransferBlocked(address from, address to);\n    /// @notice A management-fee rate above the permanent v1 cap was requested.\n    error SUSDfr_ManagementFeeTooHigh(uint16 requestedBps);\n    /// @notice A performance-fee rate above the permanent v1 cap was requested.\n    error SUSDfr_PerformanceFeeTooHigh(uint16 requestedBps);\n    /// @notice A fee checkpoint was attempted during a transient share update or\n    ///         while a cross-module fee-accounting operation was locked.\n    error SUSDfr_FeeAccrualReentrant();\n    /// @notice A two-phase fee-accounting operation was completed by the wrong caller\n    ///         or with the wrong operation type.\n    error SUSDfr_InvalidFeeOperation(address caller, uint8 expectedKind, uint8 actualKind);\n    /// @notice Share supply changed during a fee-neutral marked-NAV operation.\n    error SUSDfr_FeeOperationSupplyChanged(uint256 expectedSupply, uint256 actualSupply);\n    /// @notice A replacement fee recipient was not marked as a protocol-exempt address.\n    error SUSDfr_FeeRecipientNotExempt(address recipient);\n    /// @notice A proposed impairment source has no code or cannot return a uint256 impairment.\n    error SUSDfr_InvalidImpairmentSource(address source);\n    /// @notice A source reported less performance-fee impairment than redemption impairment.\n    error SUSDfr_InvalidPerformanceFeeImpairment(uint256 pendingImpairment, uint256 performanceImpairment);\n    /// @notice Emergency clearing was requested while the current impairment source is valid.\n    error SUSDfr_ImpairmentSourceStillReadable(address source);\n    /// @notice Emergency clearing was requested when no impairment source is configured.\n    error SUSDfr_NoImpairmentSource();\n    /// @notice Too little gas was supplied to prove source failure and finish recovery safely.\n    error SUSDfr_InsufficientImpairmentRecoveryGas(uint256 available, uint256 required);\n    /// @notice Emitted when the (fail-open) points hook reverted on a share move (P-04 telemetry).\n\n    event PointsHookFailed(address indexed from, address indexed to, uint256 value);\n    /// @notice Protocol fee shares were minted for time-based management fees.\n    event ManagementFeeAccrued(uint256 elapsed, uint256 feeAssets, uint256 feeShares);\n    /// @notice Protocol fee shares were minted on marked NAV above the global high-water mark.\n    event PerformanceFeeAccrued(\n        uint256 oldHighWaterMark, uint256 newHighWaterMark, uint256 profitAssets, uint256 feeAssets, uint256 feeShares\n    );\n    /// @notice A fee-neutral flow adjusted the global high-water mark.\n    event HighWaterMarkAdjusted(uint256 oldHighWaterMark, uint256 newHighWaterMark);\n    /// @notice An authorized module checkpointed fees and locked a junior-capacity operation.\n    event FeeNeutralMarkedNavChangeStarted(address indexed module, uint256 supply);\n    /// @notice The authorized junior-capacity operation released its checkpoint lock.\n    event FeeNeutralMarkedNavChangeCompleted(address indexed module, uint256 supply);\n    /// @notice The WaterfallEngine locked fee checkpoints before delivering senior yield.\n    event YieldNotificationStarted(address indexed module);\n    /// @notice Governance cleared a fee-operation lock left behind by a faulty trusted module.\n    event FeeOperationEmergencyCleared(address indexed module, uint8 indexed operationKind);\n    /// @notice The queue prepared one settlement chunk against the full remaining settlement\n    ///         outflow bound before taking any price quote.\n    /// @param maxAssets Maximum USDfr that the live settlement can still distribute.\n    /// @param projectedHeld Physical USDfr that would remain if that full bound left the vault.\n    /// @param instantlyRecognized Previously-unvested yield released before pricing.\n    event RedemptionPricingPrepared(uint256 maxAssets, uint256 projectedHeld, uint256 instantlyRecognized);\n    /// @notice Timelocked governance changed the prospective annual management-fee rate.\n    event ManagementFeeSet(uint16 oldFeeBps, uint16 newFeeBps);\n    /// @notice Timelocked governance changed the prospective global performance-fee rate.\n    event PerformanceFeeSet(uint16 oldFeeBps, uint16 newFeeBps);\n    /// @notice Timelocked governance changed the recipient of future vault fee shares.\n    event VaultFeeRecipientSet(address indexed oldRecipient, address indexed newRecipient);\n    /// @notice Timelocked governance cleared an unreadable impairment source without checkpointing it.\n    /// @dev `failureHash` commits to the failed selector and bounded return evidence, or\n    ///      to the semantically invalid pair of impairment values.\n    event ImpairmentSourceEmergencyCleared(address indexed source, bytes32 failureHash);\n\n    /// @notice Current fee-net realized exchange rate: assets per one whole sUSDfr token.\n    /// @dev Simulates fee shares due at this timestamp even before a checkpoint transaction.\n    function currentExchangeRate() external view returns (uint256);\n\n    /// @notice Crystallizes management and global high-water-mark performance fees.\n    /// @dev Permissionless. Fee shares mint to `feeRecipient`; no backing assets leave.\n    /// @return managementShares Shares minted for the time-based management fee.\n    /// @return performanceShares Shares minted for profit above the high-water mark.\n    function accrueFees() external returns (uint256 managementShares, uint256 performanceShares);\n\n    /// @notice Prepares queue redemption pricing against the live settlement's full remaining\n    ///         outflow bound, then checkpoints fees once against the prepared state.\n    /// @dev Queue-only. Using the settlement bound rather than the caller-selected request count\n    ///      makes optional-stream recognition independent of keeper chunking (G4/M-2).\n    /// @param maxAssets Maximum USDfr the settlement can still distribute.\n    /// @return instantlyRecognized Previously-unvested yield released before pricing.\n    function prepareRedemptionPricing(uint256 maxAssets) external returns (uint256 instantlyRecognized);\n\n    /// @notice Checkpoints fees and locks checkpoints before an authorized junior-capacity change.\n    /// @dev Must be paired atomically with `endFeeNeutralMarkedNavChange` by the same module.\n    ///      Junior-capacity effects are excluded by the impairment source's independent\n    ///      performance-fee view; this function never infers a capital flow from a NAV re-read.\n    function beginFeeNeutralMarkedNavChange() external;\n\n    /// @notice Releases an authorized junior-capacity operation's checkpoint lock.\n    /// @dev The caller and share supply must match the opening snapshot.\n    function endFeeNeutralMarkedNavChange() external;\n\n    /// @notice Locks vault fee checkpoints before the WaterfallEngine delivers senior yield.\n    /// @dev Must be paired atomically with `notifyYield` by the same module.\n    function beginYieldNotification() external;\n\n    /// @notice Clears a fee-operation lock that survived a successful trusted-module call.\n    /// @dev Timelocked emergency recovery only. Correct module paths open and close their\n    ///      lock atomically, so a persistent lock means the trusted caller is faulty.\n    function clearStaleFeeOperation() external;\n\n    /// @notice Current global performance-fee rate, in basis points of profit.\n    function performanceFeeBps() external view returns (uint16);\n\n    /// @notice Permanent v1 performance-fee ceiling, in basis points.\n    function maxPerformanceFeeBps() external pure returns (uint16);\n\n    /// @notice Current annualized management-fee rate, in basis points.\n    function managementFeeBps() external view returns (uint16);\n\n    /// @notice Permanent v1 management-fee ceiling, in basis points.\n    function maxManagementFeeBps() external pure returns (uint16);\n\n    /// @notice Time basis used to interpret the annual management-fee rate.\n    function managementFeeYear() external pure returns (uint64);\n\n    /// @notice Global post-fee high-water mark, in the same units as `feeExchangeRate`.\n    function highWaterMark() external view returns (uint256);\n\n    /// @notice Gross rate used for HWM accounting after fee-neutral junior-capital credit.\n    /// @dev Unlike `currentExchangeRate`, this does not simulate pending fee shares. It can be\n    ///      below the redemption-NAV rate while junior capital protects a live impairment.\n    function feeExchangeRate() external view returns (uint256);\n\n    /// @notice Recipient of sUSDfr management/performance fee shares.\n    function feeRecipient() external view returns (address);\n\n    /// @notice Last timestamp through which the management fee was accrued.\n    function lastFeeAccrual() external view returns (uint64);\n\n    /// @notice Sets the prospective management fee. Timelocked governance only.\n    function setManagementFee(uint16 feeBps) external;\n\n    /// @notice Sets the prospective performance fee. Timelocked governance only.\n    function setPerformanceFee(uint16 feeBps) external;\n\n    /// @notice Changes the recipient of future vault fee shares. Timelocked governance only.\n    function setFeeRecipient(address recipient) external;\n\n    /// @notice Clears a configured impairment source only when a bounded read demonstrably fails.\n    /// @dev Timelocked governance recovery path. It deliberately cannot replace a readable source\n    ///      or install a new source; normal changes must use the checkpointed setter. Any marked-NAV\n    ///      lift is ratcheted fee-free, permanently waiving performance fees embedded in that lift.\n    function clearUnreadableImpairmentSource() external;\n\n    /// @notice Sets or clears the conservative marked-NAV impairment source.\n    /// @dev Timelocked governance only. A non-zero replacement must pass an ABI read before\n    ///      the old valuation period is checkpointed and the replacement is stored.\n    function setImpairmentSource(address source) external;\n\n    /// @notice Current conservative marked-NAV impairment source, or zero when unwired.\n    function impairmentSource() external view returns (address);\n\n    /// @notice The redemption queue module (sole permitted caller of withdraw/redeem).\n    function redemptionQueue() external view returns (address);\n\n    /// @notice Sets the redemption queue. Only DEFAULT_ADMIN_ROLE (timelocked governance).\n    function setRedemptionQueue(address queue) external;\n\n    /// @notice Recognizes realized senior yield immediately or starts optional vesting (ADR-0023).\n    /// @dev Called by the WaterfallEngine right after it delivers `amount` USDfr into the\n    ///      vault. Moves no value. With a zero vesting period, recognition and the resulting\n    ///      performance-fee checkpoint complete in the caller's repayment transaction. A\n    ///      non-zero governance setting defers recognition linearly as an optional\n    ///      market-smoothing policy. Gated by CREDIT_ROLE.\n    /// @param amount The realized yield just delivered into the vault.\n    function notifyYield(uint256 amount) external;\n\n    /// @notice Realized senior yield not yet released into the exchange rate (ADR-0023).\n    function unvestedYield() external view returns (uint256);\n\n    /// @notice The asset base exits price against: realized assets LESS the\n    ///         declared-but-unrealized senior impairment (ADR-0022 Option Y).\n    /// @dev Always `<= totalAssets()`, so redemption NAV <= deposit NAV.\n    function redemptionTotalAssets() external view returns (uint256);\n\n    /// @notice Shares that `assets` buys at the conservative redemption NAV, rounded DOWN.\n    /// @dev The floor-rounded counterpart to `previewWithdraw` (which rounds up). The queue caps\n    ///      its settlement budget with this so `previewRedeem(result) <= assets` holds by\n    ///      construction and settlement can never distribute above the budget (CLAUDE.md §1.3).\n    /// @param assets The budget, in USDfr.\n    /// @return The largest share count whose conservative redemption value does not exceed `assets`.\n    function convertToSharesAtRedemption(uint256 assets) external view returns (uint256);\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC165} from \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC-721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n    /**\n     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n    /**\n     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n     */\n    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n    /**\n     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n     */\n    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n    /**\n     * @dev Returns the number of tokens in ``owner``'s account.\n     */\n    function balanceOf(address owner) external view returns (uint256 balance);\n\n    /**\n     * @dev Returns the owner of the `tokenId` token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function ownerOf(uint256 tokenId) external view returns (address owner);\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon\n     *   a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n     * are aware of the ERC-721 protocol to prevent tokens from being forever locked.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or\n     *   {setApprovalForAll}.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon\n     *   a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(address from, address to, uint256 tokenId) external;\n\n    /**\n     * @dev Transfers `tokenId` token from `from` to `to`.\n     *\n     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721\n     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must\n     * understand this adds an external call which potentially creates a reentrancy vulnerability.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must be owned by `from`.\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 tokenId) external;\n\n    /**\n     * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n     * The approval is cleared when the token is transferred.\n     *\n     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n     *\n     * Requirements:\n     *\n     * - The caller must own the token or be an approved operator.\n     * - `tokenId` must exist.\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address to, uint256 tokenId) external;\n\n    /**\n     * @dev Approve or remove `operator` as an operator for the caller.\n     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n     *\n     * Requirements:\n     *\n     * - The `operator` cannot be the address zero.\n     *\n     * Emits an {ApprovalForAll} event.\n     */\n    function setApprovalForAll(address operator, bool approved) external;\n\n    /**\n     * @dev Returns the account approved for `tokenId` token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function getApproved(uint256 tokenId) external view returns (address operator);\n\n    /**\n     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n     *\n     * See {setApprovalForAll}\n     */\n    function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"},{"file_path":"src/libraries/ReserveMigrationViewLib.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {IAccrualMigration} from \"../interfaces/IAccrualMigration.sol\";\nimport {ReserveAccrualStorageLib} from \"./ReserveAccrualStorageLib.sol\";\n\n/// @title ReserveMigrationViewLib\n/// @notice Read-only encoding of the bounded continuous-accrual import session.\nlibrary ReserveMigrationViewLib {\n    /// @notice Compiler-encoded preparation status, forwarded by the host's view-only return helper.\n    function progressData() public view returns (bytes memory) {\n        ReserveAccrualStorageLib.Migration storage m = ReserveAccrualStorageLib.state().migration;\n        return abi.encode(\n            IAccrualMigration.Progress({\n                nonce: m.nonce,\n                sessionKey: m.sessionKey,\n                cutoff: m.cutoff,\n                expected: m.expected,\n                imported: m.imported,\n                originalFace: m.originalFace,\n                importedOriginalFace: m.importedOriginalFace,\n                nextFacilityId: m.imported < m.expected ? m.facilityIds[m.imported] : 0,\n                active: m.active\n            })\n        );\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol","source_code":"// 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"},{"file_path":"lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC6093.sol)\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-20.\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"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/token/ERC721/ERC721Upgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721} from \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\nimport {IERC721Metadata} from \"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol\";\nimport {ERC721Utils} from \"@openzeppelin/contracts/token/ERC721/utils/ERC721Utils.sol\";\nimport {ContextUpgradeable} from \"../../utils/ContextUpgradeable.sol\";\nimport {Strings} from \"@openzeppelin/contracts/utils/Strings.sol\";\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {ERC165Upgradeable} from \"../../utils/introspection/ERC165Upgradeable.sol\";\nimport {IERC721Errors} from \"@openzeppelin/contracts/interfaces/draft-IERC6093.sol\";\nimport {Initializable} from \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC-721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\nabstract contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721, IERC721Metadata, IERC721Errors {\n    using Strings for uint256;\n\n    /// @custom:storage-location erc7201:openzeppelin.storage.ERC721\n    struct ERC721Storage {\n        // Token name\n        string _name;\n\n        // Token symbol\n        string _symbol;\n\n        mapping(uint256 tokenId => address) _owners;\n\n        mapping(address owner => uint256) _balances;\n\n        mapping(uint256 tokenId => address) _tokenApprovals;\n\n        mapping(address owner => mapping(address operator => bool)) _operatorApprovals;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ERC721\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant ERC721StorageLocation = 0x80bb2b638cc20bc4d0a60d66940f3ab4a00c1d7b313497ca82fb0b4ab0079300;\n\n    function _getERC721Storage() private pure returns (ERC721Storage storage $) {\n        assembly {\n            $.slot := ERC721StorageLocation\n        }\n    }\n\n    /**\n     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n     */\n    function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {\n        __ERC721_init_unchained(name_, symbol_);\n    }\n\n    function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n        ERC721Storage storage $ = _getERC721Storage();\n        $._name = name_;\n        $._symbol = symbol_;\n    }\n\n    /// @inheritdoc IERC165\n    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165) returns (bool) {\n        return\n            interfaceId == type(IERC721).interfaceId ||\n            interfaceId == type(IERC721Metadata).interfaceId ||\n            super.supportsInterface(interfaceId);\n    }\n\n    /// @inheritdoc IERC721\n    function balanceOf(address owner) public view virtual returns (uint256) {\n        ERC721Storage storage $ = _getERC721Storage();\n        if (owner == address(0)) {\n            revert ERC721InvalidOwner(address(0));\n        }\n        return $._balances[owner];\n    }\n\n    /// @inheritdoc IERC721\n    function ownerOf(uint256 tokenId) public view virtual returns (address) {\n        return _requireOwned(tokenId);\n    }\n\n    /// @inheritdoc IERC721Metadata\n    function name() public view virtual returns (string memory) {\n        ERC721Storage storage $ = _getERC721Storage();\n        return $._name;\n    }\n\n    /// @inheritdoc IERC721Metadata\n    function symbol() public view virtual returns (string memory) {\n        ERC721Storage storage $ = _getERC721Storage();\n        return $._symbol;\n    }\n\n    /// @inheritdoc IERC721Metadata\n    function tokenURI(uint256 tokenId) public view virtual returns (string memory) {\n        _requireOwned(tokenId);\n\n        string memory baseURI = _baseURI();\n        return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : \"\";\n    }\n\n    /**\n     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n     * by default, can be overridden in child contracts.\n     */\n    function _baseURI() internal view virtual returns (string memory) {\n        return \"\";\n    }\n\n    /// @inheritdoc IERC721\n    function approve(address to, uint256 tokenId) public virtual {\n        _approve(to, tokenId, _msgSender());\n    }\n\n    /// @inheritdoc IERC721\n    function getApproved(uint256 tokenId) public view virtual returns (address) {\n        _requireOwned(tokenId);\n\n        return _getApproved(tokenId);\n    }\n\n    /// @inheritdoc IERC721\n    function setApprovalForAll(address operator, bool approved) public virtual {\n        _setApprovalForAll(_msgSender(), operator, approved);\n    }\n\n    /// @inheritdoc IERC721\n    function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {\n        ERC721Storage storage $ = _getERC721Storage();\n        return $._operatorApprovals[owner][operator];\n    }\n\n    /// @inheritdoc IERC721\n    function transferFrom(address from, address to, uint256 tokenId) public virtual {\n        if (to == address(0)) {\n            revert ERC721InvalidReceiver(address(0));\n        }\n        // Setting an \"auth\" arguments enables the `_isAuthorized` check which verifies that the token exists\n        // (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.\n        address previousOwner = _update(to, tokenId, _msgSender());\n        if (previousOwner != from) {\n            revert ERC721IncorrectOwner(from, tokenId, previousOwner);\n        }\n    }\n\n    /// @inheritdoc IERC721\n    function safeTransferFrom(address from, address to, uint256 tokenId) public {\n        safeTransferFrom(from, to, tokenId, \"\");\n    }\n\n    /// @inheritdoc IERC721\n    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {\n        transferFrom(from, to, tokenId);\n        ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);\n    }\n\n    /**\n     * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist\n     *\n     * IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the\n     * core ERC-721 logic MUST be matched with the use of {_increaseBalance} to keep balances\n     * consistent with ownership. The invariant to preserve is that for any address `a` the value returned by\n     * `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.\n     */\n    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {\n        ERC721Storage storage $ = _getERC721Storage();\n        return $._owners[tokenId];\n    }\n\n    /**\n     * @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.\n     */\n    function _getApproved(uint256 tokenId) internal view virtual returns (address) {\n        ERC721Storage storage $ = _getERC721Storage();\n        return $._tokenApprovals[tokenId];\n    }\n\n    /**\n     * @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in\n     * particular (ignoring whether it is owned by `owner`).\n     *\n     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this\n     * assumption.\n     */\n    function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {\n        return\n            spender != address(0) &&\n            (owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);\n    }\n\n    /**\n     * @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.\n     * Reverts if:\n     * - `spender` does not have approval from `owner` for `tokenId`.\n     * - `spender` does not have approval to manage all of `owner`'s assets.\n     *\n     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this\n     * assumption.\n     */\n    function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {\n        if (!_isAuthorized(owner, spender, tokenId)) {\n            if (owner == address(0)) {\n                revert ERC721NonexistentToken(tokenId);\n            } else {\n                revert ERC721InsufficientApproval(spender, tokenId);\n            }\n        }\n    }\n\n    /**\n     * @dev Unsafe write access to the balances, used by extensions that \"mint\" tokens using an {ownerOf} override.\n     *\n     * NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that\n     * a uint256 would ever overflow from increments when these increments are bounded to uint128 values.\n     *\n     * WARNING: Increasing an account's balance using this function tends to be paired with an override of the\n     * {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership\n     * remain consistent with one another.\n     */\n    function _increaseBalance(address account, uint128 value) internal virtual {\n        ERC721Storage storage $ = _getERC721Storage();\n        unchecked {\n            $._balances[account] += value;\n        }\n    }\n\n    /**\n     * @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner\n     * (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.\n     *\n     * The `auth` argument is optional. If the value passed is non 0, then this function will check that\n     * `auth` is either the owner of the token, or approved to operate on the token (by the owner).\n     *\n     * Emits a {Transfer} event.\n     *\n     * NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.\n     */\n    function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {\n        ERC721Storage storage $ = _getERC721Storage();\n        address from = _ownerOf(tokenId);\n\n        // Perform (optional) operator check\n        if (auth != address(0)) {\n            _checkAuthorized(from, auth, tokenId);\n        }\n\n        // Execute the update\n        if (from != address(0)) {\n            // Clear approval. No need to re-authorize or emit the Approval event\n            _approve(address(0), tokenId, address(0), false);\n\n            unchecked {\n                $._balances[from] -= 1;\n            }\n        }\n\n        if (to != address(0)) {\n            unchecked {\n                $._balances[to] += 1;\n            }\n        }\n\n        $._owners[tokenId] = to;\n\n        emit Transfer(from, to, tokenId);\n\n        return from;\n    }\n\n    /**\n     * @dev Mints `tokenId` and transfers it to `to`.\n     *\n     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n     *\n     * Requirements:\n     *\n     * - `tokenId` must not exist.\n     * - `to` cannot be the zero address.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _mint(address to, uint256 tokenId) internal {\n        if (to == address(0)) {\n            revert ERC721InvalidReceiver(address(0));\n        }\n        address previousOwner = _update(to, tokenId, address(0));\n        if (previousOwner != address(0)) {\n            revert ERC721InvalidSender(address(0));\n        }\n    }\n\n    /**\n     * @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must not exist.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _safeMint(address to, uint256 tokenId) internal {\n        _safeMint(to, tokenId, \"\");\n    }\n\n    /**\n     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n     */\n    function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {\n        _mint(to, tokenId);\n        ERC721Utils.checkOnERC721Received(_msgSender(), address(0), to, tokenId, data);\n    }\n\n    /**\n     * @dev Destroys `tokenId`.\n     * The approval is cleared when the token is burned.\n     * This is an internal function that does not check if the sender is authorized to operate on the token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _burn(uint256 tokenId) internal {\n        address previousOwner = _update(address(0), tokenId, address(0));\n        if (previousOwner == address(0)) {\n            revert ERC721NonexistentToken(tokenId);\n        }\n    }\n\n    /**\n     * @dev Transfers `tokenId` from `from` to `to`.\n     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must be owned by `from`.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _transfer(address from, address to, uint256 tokenId) internal {\n        if (to == address(0)) {\n            revert ERC721InvalidReceiver(address(0));\n        }\n        address previousOwner = _update(to, tokenId, address(0));\n        if (previousOwner == address(0)) {\n            revert ERC721NonexistentToken(tokenId);\n        } else if (previousOwner != from) {\n            revert ERC721IncorrectOwner(from, tokenId, previousOwner);\n        }\n    }\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients\n     * are aware of the ERC-721 standard to prevent tokens from being forever locked.\n     *\n     * `data` is additional data, it has no specified format and it is sent in call to `to`.\n     *\n     * This internal function is like {safeTransferFrom} in the sense that it invokes\n     * {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.\n     * implement alternative mechanisms to perform token transfer, such as signature-based.\n     *\n     * Requirements:\n     *\n     * - `tokenId` token must exist and be owned by `from`.\n     * - `to` cannot be the zero address.\n     * - `from` cannot be the zero address.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _safeTransfer(address from, address to, uint256 tokenId) internal {\n        _safeTransfer(from, to, tokenId, \"\");\n    }\n\n    /**\n     * @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is\n     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n     */\n    function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {\n        _transfer(from, to, tokenId);\n        ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);\n    }\n\n    /**\n     * @dev Approve `to` to operate on `tokenId`\n     *\n     * The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is\n     * either the owner of the token, or approved to operate on all tokens held by this owner.\n     *\n     * Emits an {Approval} event.\n     *\n     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\n     */\n    function _approve(address to, uint256 tokenId, address auth) internal {\n        _approve(to, tokenId, auth, true);\n    }\n\n    /**\n     * @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not\n     * emitted in the context of transfers.\n     */\n    function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {\n        ERC721Storage storage $ = _getERC721Storage();\n        // Avoid reading the owner unless necessary\n        if (emitEvent || auth != address(0)) {\n            address owner = _requireOwned(tokenId);\n\n            // We do not use _isAuthorized because single-token approvals should not be able to call approve\n            if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {\n                revert ERC721InvalidApprover(auth);\n            }\n\n            if (emitEvent) {\n                emit Approval(owner, to, tokenId);\n            }\n        }\n\n        $._tokenApprovals[tokenId] = to;\n    }\n\n    /**\n     * @dev Approve `operator` to operate on all of `owner` tokens\n     *\n     * Requirements:\n     * - operator can't be the address zero.\n     *\n     * Emits an {ApprovalForAll} event.\n     */\n    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {\n        ERC721Storage storage $ = _getERC721Storage();\n        if (operator == address(0)) {\n            revert ERC721InvalidOperator(operator);\n        }\n        $._operatorApprovals[owner][operator] = approved;\n        emit ApprovalForAll(owner, operator, approved);\n    }\n\n    /**\n     * @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).\n     * Returns the owner.\n     *\n     * Overrides to ownership logic should be done to {_ownerOf}.\n     */\n    function _requireOwned(uint256 tokenId) internal view returns (address) {\n        address owner = _ownerOf(tokenId);\n        if (owner == address(0)) {\n            revert ERC721NonexistentToken(tokenId);\n        }\n        return owner;\n    }\n}\n"},{"file_path":"src/libraries/ReserveAccrualServiceLib.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {ReserveManager} from \"../ReserveManager.sol\";\n\nimport {ClaimBridge} from \"../ClaimBridge.sol\";\nimport {IAccrualBridge} from \"../interfaces/IAccrualLifecycle.sol\";\nimport {AccrualLoans} from \"./AccrualLoans.sol\";\nimport {ReserveAccrualLib} from \"./ReserveAccrualLib.sol\";\nimport {ReserveAccrualStorageLib} from \"./ReserveAccrualStorageLib.sol\";\nimport {ReserveStorageLib} from \"./ReserveStorageLib.sol\";\n\n/// @title ReserveAccrualServiceLib\n/// @notice Bounded signed-date servicing without resetting a positive interest curve.\nlibrary ReserveAccrualServiceLib {\n    using AccrualLoans for AccrualLoans.State;\n\n    error AccrualService_UnknownFacility(uint256 facilityId);\n    error AccrualService_InvalidCeiling();\n\n    event AccrualBoundaryProcessed(\n        uint256 indexed facilityId, uint64 indexed at, uint256 capitalized, uint64 nextDue, bool stopped\n    );\n    event AccrualCeilingReserved(uint256 indexed facilityId, uint256 previousCeiling, uint256 nextCeiling);\n    /// @notice Commits only dormant signed-date work; positive scheduled curves are left intact.\n\n    function service(ReserveManager.ReserveStorage storage native, uint256 id) public returns (uint256 capitalized) {\n        ReserveAccrualLib.requireFresh();\n        ReserveAccrualStorageLib.State storage s = _known(id);\n        s.busy = true;\n        AccrualLoans.LifecycleWork memory work = s.loans.serviceDormant(id, ReserveAccrualStorageLib.now64());\n        capitalized = work.capitalized;\n        AccrualLoans.Loan storage loan = s.loans.loans[id];\n        if (loan.mixed && work.previousDue != 0) {\n            IAccrualBridge(s.modules.bridge).setAccruedPaymentDue(id, work.nextDue);\n        } else if (work.nextDue != 0 && work.nextDue > ClaimBridge(s.modules.bridge).facility(id).nextPaymentDue) {\n            IAccrualBridge(s.modules.bridge).setAccruedPaymentDue(id, work.nextDue);\n        }\n        if (work.stopped) {\n            uint256 face = native.deployed[id] + ReserveAccrualStorageLib.facilityUnposted(id);\n            _trimCeiling(s, id, face);\n        }\n        s.busy = false;\n        emit AccrualBoundaryProcessed(id, work.at, capitalized, work.nextDue, work.stopped);\n    }\n\n    /// @notice Whether this known facility has positive chronological work in the bounded queue.\n    function scheduled(uint256 id) public view returns (bool) {\n        ReserveAccrualStorageLib.State storage s = _known(id);\n        return s.loans.book.entries[id].scheduled;\n    }\n\n    function _known(uint256 id) private view returns (ReserveAccrualStorageLib.State storage s) {\n        s = ReserveAccrualStorageLib.state();\n        if (!s.enabled || !s.identities[id].known) revert AccrualService_UnknownFacility(id);\n    }\n\n    function _trimCeiling(ReserveAccrualStorageLib.State storage s, uint256 id, uint256 face) private {\n        uint256 prior = s.identities[id].reservedCeiling;\n        if (face > prior) revert AccrualService_InvalidCeiling();\n        s.reservedCeilings -= prior - face;\n        s.identities[id].reservedCeiling = face;\n        emit AccrualCeilingReserved(id, prior, face);\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol","source_code":"// 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"},{"file_path":"src/libraries/ReserveAccrualViewsLib.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {ReserveManager} from \"../ReserveManager.sol\";\nimport {ReserveStorageLib} from \"./ReserveStorageLib.sol\";\nimport {IAccrualLifecycle} from \"../interfaces/IAccrualLifecycle.sol\";\nimport {AccrualLoans} from \"./AccrualLoans.sol\";\nimport {ReserveAccrualStorageLib} from \"./ReserveAccrualStorageLib.sol\";\n/// @notice Typed constant-time debt views for Ethereum's reserve-owned accrual book.\n\nlibrary ReserveAccrualViewsLib {\n    using AccrualLoans for AccrualLoans.State;\n\n    function debt(uint256 id) public view returns (bytes memory) {\n        IAccrualLifecycle.Debt memory d;\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        if (!s.enabled || !s.identities[id].known) return abi.encode(d);\n        AccrualLoans.Loan storage loan = s.loans.loans[id];\n        (d.principal, d.interest, d.accruedThrough) = s.loans.loanFace(id, ReserveAccrualStorageLib.now64());\n        d.balanceCeiling = loan.balanceCeiling;\n        d.nextCapitalization = loan.nextCapitalization;\n        d.maturity = loan.legalMaturity;\n        d.pik = loan.pik;\n        d.active = loan.active;\n        d.known = true;\n        return abi.encode(d);\n    }\n\n    /// @notice Separates contractual cash and PIK balances without scanning facilities or history.\n    function interestLegs(uint256 id) public view returns (bytes memory) {\n        IAccrualLifecycle.InterestLegs memory result;\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        if (!s.enabled || !s.identities[id].known) return abi.encode(result);\n        AccrualLoans.Loan storage loan = s.loans.loans[id];\n        uint256 interest;\n        if (loan.mixed) {\n            (result.cash, result.pik, result.accruedThrough) =\n                s.loans.loanInterestLegs(id, ReserveAccrualStorageLib.now64());\n            result.mixed = true;\n        } else {\n            (, interest, result.accruedThrough) = s.loans.loanFace(id, ReserveAccrualStorageLib.now64());\n            if (loan.pik) result.pik = interest;\n            else result.cash = interest;\n        }\n        result.known = true;\n        return abi.encode(result);\n    }\n\n    /// @notice Recorded plus earned unposted native face, without enumerating facilities.\n\n    function deployed(ReserveManager.ReserveStorage storage native, uint256 id, bool total)\n        public\n        view\n        returns (uint256)\n    {\n        return total\n            ? native.totalDeployedPrincipal + ReserveAccrualStorageLib.unposted()\n            : native.deployed[id] + ReserveAccrualStorageLib.facilityUnposted(id);\n    }\n\n    /// @notice Unposted earned face for one facility, through the coherent portfolio frontier.\n    function unpostedLoan(uint256 id) public view returns (uint256) {\n        return ReserveAccrualStorageLib.facilityUnposted(id);\n    }\n\n    /// @notice Native backing with a coherent delivery snapshot. Only recognition observes custody.\n    function backing(ReserveManager.ReserveStorage storage native, bool recognized)\n        public\n        view\n        returns (uint256 value)\n    {\n        ReserveAccrualStorageLib.State storage s = ReserveAccrualStorageLib.state();\n        if (s.delivery.active) return recognized ? s.delivery.recognizedBacking : s.delivery.backing;\n        value = ReserveStorageLib.backingValue(native);\n        if (recognized) {\n            uint256 live = native.usdcToken.balanceOf(address(this));\n            uint256 shortfall =\n                native.idleUSDCUnits > live ? ReserveStorageLib.normalize(native.idleUSDCUnits - live) : 0;\n            value = value > shortfall ? value - shortfall : 0;\n        }\n    }\n}\n"},{"file_path":"src/libraries/AccrualMath.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\n\n/// @title AccrualMath — pure arithmetic on a fixed contractual interest basis\n/// @notice Computes simple interest and cumulative fractions without changing a facility's basis.\n/// @dev These primitives do not select an accrual architecture, capitalization schedule or rounding\n///      policy. In particular, interpolating `periodAmount` is not identical to applying\n///      `earnedInterest` at each instant: rounding the endpoint to a reserve unit changes the\n///      intermediate curve. With a nonbinding cap their integer outputs differ by at most one reserve\n///      unit; the unrounded endpoint interpolation differs by strictly less than one unit. A binding\n///      cap can make the difference larger. Callers must choose the contractual policy explicitly.\n///      No storage, clock reads, roles, external calls, fee allocation or token operations occur here.\nlibrary AccrualMath {\n    /// @notice The supplied basis exceeds the registry's existing maximum safe exposure.\n    /// @param basis The invalid normalized principal basis.\n    error AccrualMath_BasisTooLarge(uint256 basis);\n\n    /// @notice The annual nominal rate exceeds the protocol's existing 100% ceiling.\n    /// @param rateBps The invalid annual rate, in basis points.\n    error AccrualMath_RateTooLarge(uint16 rateBps);\n\n    /// @notice Only the unambiguous Actual/360 and Actual/365 denominators are supported.\n    /// @param yearSeconds The unsupported interest-year denominator, in seconds.\n    error AccrualMath_UnsupportedYear(uint256 yearSeconds);\n\n    /// @notice Uncapped earned interest cannot be represented in uint256.\n    /// @dev `periodAmount` can still return a valid capped result for these otherwise valid terms.\n    error AccrualMath_AmountOverflow();\n\n    /// @notice A reserve unit must contain at least one normalized wei.\n    error AccrualMath_ZeroScale();\n\n    /// @notice A cumulative linear interval must have a positive duration.\n    error AccrualMath_ZeroDuration();\n\n    /// @notice The requested cumulative elapsed time lies beyond the fixed interval.\n    /// @param elapsed The requested elapsed time, in seconds.\n    /// @param duration The fixed interval duration, in seconds.\n    error AccrualMath_ElapsedExceedsDuration(uint64 elapsed, uint64 duration);\n\n    /// @notice A delta must run forward from its earlier cumulative checkpoint.\n    /// @param previousElapsed The previous cumulative elapsed time, in seconds.\n    /// @param elapsed The new cumulative elapsed time, in seconds.\n    error AccrualMath_ReversedWindow(uint64 previousElapsed, uint64 elapsed);\n\n    /// @notice Simple interest earned over cumulative elapsed time on an unchanged basis.\n    /// @dev Floors once to normalized wei using full-precision multiplication and division. A zero\n    ///      basis, rate or elapsed time returns zero, after validating all input bounds. The uint64\n    ///      elapsed bound and the 10,000 bps ceiling make `rateBps * elapsed` safe in uint256.\n    /// @param basis Frozen normalized principal, at most uint256-max / 10,000 as in the registry.\n    /// @param rateBps Fixed annual nominal rate, from zero through 10,000 inclusive.\n    /// @param elapsed Cumulative elapsed seconds on that basis; this function does not read the clock.\n    /// @param yearSeconds Exactly 360 days or 365 days, as specified by the note.\n    /// @return amount Earned interest, rounded down to normalized wei.\n    function earnedInterest(uint256 basis, uint16 rateBps, uint64 elapsed, uint256 yearSeconds)\n        internal\n        pure\n        returns (uint256 amount)\n    {\n        uint256 denominator = _validateTerms(basis, rateBps, yearSeconds);\n        uint256 coefficient = uint256(rateBps) * elapsed;\n        (uint256 high,) = Math.mul512(basis, coefficient);\n        if (high >= denominator) revert AccrualMath_AmountOverflow();\n        amount = Math.mulDiv(basis, coefficient, denominator);\n    }\n\n    /// @notice The fixed-period amount, capped and rounded down to a whole reserve unit.\n    /// @dev Reproduces the existing PIK amount/cap/grid order. The cap is a maximum ADDITIONAL\n    ///      amount, not a total facility-balance ceiling. A cap below one reserve unit yields zero;\n    ///      deciding whether to advance a zero-amount period belongs to the servicing layer.\n    ///      A capped result remains computable even when uncapped interest would exceed uint256.\n    /// @param basis Frozen normalized principal, at most uint256-max / 10,000.\n    /// @param rateBps Fixed annual nominal rate, from zero through 10,000 inclusive.\n    /// @param duration Actual elapsed seconds in the fixed contractual period; zero is permitted.\n    /// @param yearSeconds Exactly 360 days or 365 days.\n    /// @param scale Normalized wei in one reserve unit; nonzero. Ethereum USDC uses 1e12, BSC uses 1.\n    /// @param cap Maximum additional normalized interest recognizable for this period.\n    /// @return amount The capped interest amount, a whole multiple of `scale`.\n    function periodAmount(\n        uint256 basis,\n        uint16 rateBps,\n        uint64 duration,\n        uint256 yearSeconds,\n        uint256 scale,\n        uint256 cap\n    ) internal pure returns (uint256 amount) {\n        if (scale == 0) revert AccrualMath_ZeroScale();\n        uint256 denominator = _validateTerms(basis, rateBps, yearSeconds);\n        uint256 coefficient = uint256(rateBps) * duration;\n        (uint256 high,) = Math.mul512(basis, coefficient);\n        if (high >= denominator) {\n            // The exact quotient exceeds every uint256 cap; do not evaluate an overflowing div.\n            amount = cap;\n        } else {\n            amount = Math.mulDiv(basis, coefficient, denominator);\n            if (amount > cap) amount = cap;\n        }\n        amount = (amount / scale) * scale;\n    }\n\n    /// @notice Cumulative linear fraction of an already fixed endpoint amount.\n    /// @dev Floors once to normalized wei. At zero elapsed it returns zero; at the exact duration\n    ///      it returns the endpoint, even for uint256-max amounts. This is an optional interpolation\n    ///      primitive, not a declaration that grid-rounded endpoint interpolation is contractual.\n    /// @param endpointAmount The fixed amount earned at the end of the interval.\n    /// @param duration Positive interval duration, in seconds.\n    /// @param elapsed Cumulative elapsed seconds, no greater than `duration`.\n    /// @return amount The cumulative floor-rounded fraction of `endpointAmount`.\n    function linearEarned(uint256 endpointAmount, uint64 duration, uint64 elapsed)\n        internal\n        pure\n        returns (uint256 amount)\n    {\n        if (duration == 0) revert AccrualMath_ZeroDuration();\n        if (elapsed > duration) revert AccrualMath_ElapsedExceedsDuration(elapsed, duration);\n        amount = Math.mulDiv(endpointAmount, elapsed, duration);\n    }\n\n    /// @notice Newly earned amount between two cumulative linear checkpoints.\n    /// @dev Subtracts cumulative floors, so arbitrary adjacent checkpoints telescope exactly.\n    ///      Flooring `endpointAmount * (elapsed - previousElapsed) / duration` instead would discard\n    ///      a fresh remainder at every call and make earned value depend on checkpoint frequency.\n    /// @param endpointAmount The fixed amount earned at the end of the interval.\n    /// @param duration Positive interval duration, in seconds.\n    /// @param previousElapsed Earlier cumulative elapsed seconds.\n    /// @param elapsed Later cumulative elapsed seconds, at most `duration`.\n    /// @return amount Incremental earned amount between the two checkpoints.\n    function linearDelta(uint256 endpointAmount, uint64 duration, uint64 previousElapsed, uint64 elapsed)\n        internal\n        pure\n        returns (uint256 amount)\n    {\n        if (previousElapsed > elapsed) revert AccrualMath_ReversedWindow(previousElapsed, elapsed);\n        amount =\n            linearEarned(endpointAmount, duration, elapsed) - linearEarned(endpointAmount, duration, previousElapsed);\n    }\n\n    /// @dev Validates the existing admission bounds and returns the positive interest denominator.\n    function _validateTerms(uint256 basis, uint16 rateBps, uint256 yearSeconds)\n        private\n        pure\n        returns (uint256 denominator)\n    {\n        if (basis > type(uint256).max / 10_000) revert AccrualMath_BasisTooLarge(basis);\n        if (rateBps > 10_000) revert AccrualMath_RateTooLarge(rateBps);\n        if (yearSeconds != 360 days && yearSeconds != 365 days) {\n            revert AccrualMath_UnsupportedYear(yearSeconds);\n        }\n        denominator = 10_000 * yearSeconds;\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/Address.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\nimport {Errors} from \"./Errors.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\n        (bool success, bytes memory returndata) = recipient.call{value: amount}(\"\");\n        if (!success) {\n            _revert(returndata);\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, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata);\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, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\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, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\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    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata\n    ) internal view returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\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 (returndata.length == 0 && target.code.length == 0) {\n                revert AddressEmptyCode(target);\n            }\n            return returndata;\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            _revert(returndata);\n        } else {\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.\n     */\n    function _revert(bytes memory returndata) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            assembly (\"memory-safe\") {\n                revert(add(returndata, 0x20), mload(returndata))\n            }\n        } else {\n            revert Errors.FailedCall();\n        }\n    }\n}\n"},{"file_path":"src/interfaces/IReserveLossAbsorber.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.30;\n\n/// @title IReserveLossAbsorber — reserve-loss allocation shape and retained compatibility hook\n/// @notice The bound implementation remains ReserveManager's canonical loss-book identity and this\n///         interface defines the allocation record shared by its live custody cascade. In the\n///         current tree ReserveManager performs that cascade internally; no production source calls\n///         `absorbReserveLoss`.\ninterface IReserveLossAbsorber {\n    /// @notice Exact allocation of one reserve-custody backing reduction.\n    /// @dev `curatorAbsorbed + backstopCovered + seniorBurned` is the supply burned. Together\n    ///      with `residualDeficit`, it must equal the portion not absorbed by existing surplus.\n    struct ReserveLossAllocation {\n        uint256 surplusAbsorbed;\n        uint256 curatorAbsorbed;\n        uint256 backstopCovered;\n        uint256 seniorBurned;\n        uint256 residualDeficit;\n    }\n\n    /// @notice The ReserveManager this absorber is bound to.\n    /// @dev Used when wiring the hook so a loss absorber cannot be installed against the wrong\n    ///      reserve accounting source.\n    function reserveLossSource() external view returns (address);\n\n    /// @notice Retained compatibility entry for allocating a pending reserve-backing loss.\n    /// @dev The entry remains caller- and namespace-guarded, but the live production path is\n    ///      `ReserveManager._absorbRecognizedReserveLoss -> _drawJuniorReserveLoss`. The retained\n    ///      entry emits no transition event and must not be counted as coverage of that live path.\n    /// @param incidentId Governance-opened upper-namespace event id reused by every partial\n    ///        write-down belonging to the same custody incident.\n    /// @param requiredSupplyReduction The supply that must be burned or latched as a residual\n    ///        deficit, in 18-decimal USDfr units.\n    function absorbReserveLoss(uint256 incidentId, uint256 requiredSupplyReduction)\n        external\n        returns (ReserveLossAllocation memory allocation);\n}\n"}],"certified":false,"conflicting_implementations":null,"abi":[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AccessControlBadConfirmation","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bytes32","name":"neededRole","type":"bytes32"}],"name":"AccessControlUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"}],"name":"AccrualCredit_UseAccrualLifecycle","type":"error"},{"inputs":[{"internalType":"address","name":"expected","type":"address"},{"internalType":"address","name":"caller","type":"address"}],"name":"AccrualCredit_WrongCaller","type":"error"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"registry","type":"address"}],"name":"BorrowerPayout_InvalidRegistry","type":"error"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"}],"name":"BorrowerPayout_RecipientNotAllowed","type":"error"},{"inputs":[{"internalType":"address","name":"registry","type":"address"}],"name":"BorrowerPayout_RegistryAlreadySet","type":"error"},{"inputs":[{"internalType":"address","name":"implementation","type":"address"}],"name":"ERC1967InvalidImplementation","type":"error"},{"inputs":[],"name":"ERC1967NonPayable","type":"error"},{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[],"name":"FailedCall","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[{"internalType":"uint256","name":"armId","type":"uint256"}],"name":"LossEventIds_InvalidCustodyArm","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[],"name":"ReserveAccrual_OperationInProgress","type":"error"},{"inputs":[{"internalType":"uint256","name":"armId","type":"uint256"}],"name":"ReserveManager_ArmAlreadyActive","type":"error"},{"inputs":[{"internalType":"uint256","name":"armId","type":"uint256"}],"name":"ReserveManager_ArmAlreadyRatified","type":"error"},{"inputs":[{"internalType":"bytes32","name":"expected","type":"bytes32"},{"internalType":"bytes32","name":"supplied","type":"bytes32"}],"name":"ReserveManager_ArmEvidenceMismatch","type":"error"},{"inputs":[],"name":"ReserveManager_ArmIdExhausted","type":"error"},{"inputs":[{"internalType":"uint256","name":"expected","type":"uint256"},{"internalType":"uint256","name":"supplied","type":"uint256"}],"name":"ReserveManager_ArmMismatch","type":"error"},{"inputs":[{"internalType":"uint256","name":"recordedDeficit","type":"uint256"}],"name":"ReserveManager_DeficitResolutionRequired","type":"error"},{"inputs":[{"internalType":"uint256","name":"recordedDeficit","type":"uint256"},{"internalType":"uint256","name":"observedDeficit","type":"uint256"}],"name":"ReserveManager_DeficitStillExists","type":"error"},{"inputs":[],"name":"ReserveManager_GuardianArmsDisabled","type":"error"},{"inputs":[{"internalType":"uint256","name":"recordedUnits","type":"uint256"},{"internalType":"uint256","name":"liveUnits","type":"uint256"}],"name":"ReserveManager_IdleCustodyShortfall","type":"error"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"},{"internalType":"uint256","name":"requested","type":"uint256"},{"internalType":"uint256","name":"remainingFace","type":"uint256"}],"name":"ReserveManager_ImpairmentExceedsFace","type":"error"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"},{"internalType":"uint256","name":"requested","type":"uint256"},{"internalType":"uint256","name":"recognized","type":"uint256"}],"name":"ReserveManager_ImpairmentReleaseExceedsRecognized","type":"error"},{"inputs":[{"internalType":"uint256","name":"incidentId","type":"uint256"}],"name":"ReserveManager_IncidentAlreadyActive","type":"error"},{"inputs":[{"internalType":"uint256","name":"incidentId","type":"uint256"}],"name":"ReserveManager_IncidentAlreadyUsed","type":"error"},{"inputs":[{"internalType":"uint256","name":"expected","type":"uint256"},{"internalType":"uint256","name":"supplied","type":"uint256"}],"name":"ReserveManager_IncidentMismatch","type":"error"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"},{"internalType":"uint256","name":"requested","type":"uint256"},{"internalType":"uint256","name":"deployed","type":"uint256"}],"name":"ReserveManager_InsufficientDeployedPrincipal","type":"error"},{"inputs":[{"internalType":"uint256","name":"requestedValue","type":"uint256"},{"internalType":"uint256","name":"idleValue","type":"uint256"}],"name":"ReserveManager_InsufficientIdleValue","type":"error"},{"inputs":[],"name":"ReserveManager_InterlockReleaseForbidden","type":"error"},{"inputs":[{"internalType":"address","name":"governor","type":"address"},{"internalType":"address","name":"timelock","type":"address"}],"name":"ReserveManager_InvalidGovernanceTiming","type":"error"},{"inputs":[{"internalType":"uint256","name":"incidentNonce","type":"uint256"}],"name":"ReserveManager_InvalidIncidentNonce","type":"error"},{"inputs":[{"internalType":"address","name":"absorber","type":"address"}],"name":"ReserveManager_InvalidLossAbsorber","type":"error"},{"inputs":[{"internalType":"address","name":"controller","type":"address"}],"name":"ReserveManager_InvalidLossController","type":"error"},{"inputs":[{"internalType":"uint256","name":"incidentId","type":"uint256"}],"name":"ReserveManager_InvalidReserveLossIncident","type":"error"},{"inputs":[{"internalType":"uint8","name":"decimals","type":"uint8"}],"name":"ReserveManager_InvalidUSDCDecimals","type":"error"},{"inputs":[],"name":"ReserveManager_LegacyPathDisabled","type":"error"},{"inputs":[],"name":"ReserveManager_LegacyRollbackUnsafe","type":"error"},{"inputs":[{"internalType":"uint256","name":"nativeUnits","type":"uint256"}],"name":"ReserveManager_LiveShortfallExists","type":"error"},{"inputs":[{"internalType":"uint256","name":"backingReduction","type":"uint256"},{"internalType":"uint256","name":"supplyBurned","type":"uint256"}],"name":"ReserveManager_LossAbsorberContractViolated","type":"error"},{"inputs":[{"internalType":"uint256","name":"expectedSurplus","type":"uint256"},{"internalType":"uint256","name":"reportedSurplus","type":"uint256"},{"internalType":"uint256","name":"expectedAccounted","type":"uint256"},{"internalType":"uint256","name":"reportedAccounted","type":"uint256"}],"name":"ReserveManager_LossAllocationMismatch","type":"error"},{"inputs":[{"internalType":"uint256","name":"actualLoss","type":"uint256"},{"internalType":"uint256","name":"approvedMaxLoss","type":"uint256"}],"name":"ReserveManager_LossExceedsApproval","type":"error"},{"inputs":[],"name":"ReserveManager_ModuleRebindForbidden","type":"error"},{"inputs":[],"name":"ReserveManager_NoActiveArm","type":"error"},{"inputs":[],"name":"ReserveManager_NoActiveIncident","type":"error"},{"inputs":[],"name":"ReserveManager_NoRecognizedReserveLoss","type":"error"},{"inputs":[{"internalType":"uint256","name":"armId","type":"uint256"}],"name":"ReserveManager_NoRecoveredUSDC","type":"error"},{"inputs":[],"name":"ReserveManager_NoReserveDeficit","type":"error"},{"inputs":[],"name":"ReserveManager_NoValueReceived","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"ReserveManager_NotDepositor","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"ReserveManager_NotLossAbsorber","type":"error"},{"inputs":[{"internalType":"uint256","name":"expectedDeficit","type":"uint256"},{"internalType":"uint256","name":"observedDeficit","type":"uint256"}],"name":"ReserveManager_PostLossDeficitMismatch","type":"error"},{"inputs":[{"internalType":"uint256","name":"principal","type":"uint256"},{"internalType":"uint256","name":"paymentValue","type":"uint256"}],"name":"ReserveManager_PrincipalExceedsPayment","type":"error"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ReserveManager_RecognizedLossOutstanding","type":"error"},{"inputs":[{"internalType":"uint256","name":"armId","type":"uint256"},{"internalType":"uint256","name":"nativeUnits","type":"uint256"}],"name":"ReserveManager_RecoveredUSDCNotCredited","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"ReserveManager_ReserveLossCallerNotAdmin","type":"error"},{"inputs":[],"name":"ReserveManager_SelfDeployment","type":"error"},{"inputs":[],"name":"ReserveManager_ShortfallCured","type":"error"},{"inputs":[{"internalType":"uint256","name":"expected","type":"uint256"},{"internalType":"uint256","name":"received","type":"uint256"}],"name":"ReserveManager_UnexpectedUSDCReceipt","type":"error"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"name":"ReserveManager_ValueNotUSDCExact","type":"error"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"idle","type":"uint256"}],"name":"ReserveManager_WriteDownExceedsIdle","type":"error"},{"inputs":[],"name":"ReserveManager_ZeroAddress","type":"error"},{"inputs":[],"name":"ReserveManager_ZeroAmount","type":"error"},{"inputs":[],"name":"ReserveManager_ZeroEvidenceHash","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"UUPSUnauthorizedCallContext","type":"error"},{"inputs":[{"internalType":"bytes32","name":"slot","type":"bytes32"}],"name":"UUPSUnsupportedProxiableUUID","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"registry","type":"address"}],"name":"BorrowerPayoutRegistrySet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"incidentId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"consumed","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"outstanding","type":"uint256"}],"name":"ExitPrepaymentAbsorbedByCustody","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"facilityId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"consumed","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"outstanding","type":"uint256"}],"name":"ExitPrepaymentConsumed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"outstanding","type":"uint256"}],"name":"ExitPrepaymentRecorded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"facilityId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"FeeCapitalized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"enabled","type":"bool"}],"name":"GuardianReserveLossArmsEnabled","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"recorded","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"live","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shortfall","type":"uint256"}],"name":"IdleUSDCObserved","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"remaining","type":"uint256"}],"name":"IdleUSDCWrittenDown","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousAbsorber","type":"address"},{"indexed":true,"internalType":"address","name":"newAbsorber","type":"address"}],"name":"LossAbsorberSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousController","type":"address"},{"indexed":true,"internalType":"address","name":"newController","type":"address"}],"name":"LossControllerSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"facilityId","type":"uint256"},{"indexed":true,"internalType":"address","name":"payer","type":"address"},{"indexed":false,"internalType":"uint256","name":"usdcAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"principalReturned","type":"uint256"}],"name":"PaymentReceived","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"facilityId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"deployedAfter","type":"uint256"}],"name":"PikCapitalized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"facilityId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"PrincipalDeployed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"facilityId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"facilityImpairment","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalImpairment","type":"uint256"}],"name":"PrincipalImpairmentRealized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"facilityId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"facilityImpairment","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalImpairment","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"backingAfter","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"evidenceHash","type":"bytes32"}],"name":"PrincipalImpairmentRecognized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"facilityId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"facilityImpairment","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalImpairment","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"evidenceHash","type":"bytes32"}],"name":"PrincipalImpairmentReleased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"facilityId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"PrincipalWrittenDown","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"funder","type":"address"},{"indexed":false,"internalType":"uint256","name":"units","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"credited","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"backingAfter","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"deficitOutstanding","type":"uint256"}],"name":"Recapitalized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"armId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"nativeUnits","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"},{"indexed":true,"internalType":"bytes32","name":"evidenceHash","type":"bytes32"}],"name":"RecoveredIdleUSDCCredited","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"previousDeficit","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"evidenceHash","type":"bytes32"}],"name":"ReserveDeficitResolved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"incidentId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"previousDeficit","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"currentDeficit","type":"uint256"}],"name":"ReserveDeficitUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"incidentId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"backingReduction","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"surplusAbsorbed","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"curatorAbsorbed","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"backstopCovered","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"seniorBurned","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"residualDeficit","type":"uint256"}],"name":"ReserveLossAllocated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"armId","type":"uint256"},{"indexed":true,"internalType":"bytes32","name":"evidenceHash","type":"bytes32"}],"name":"ReserveLossArmCancelled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"armId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"incidentId","type":"uint256"},{"indexed":true,"internalType":"bytes32","name":"evidenceHash","type":"bytes32"}],"name":"ReserveLossArmFinalized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"armId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"incidentId","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"evidenceHash","type":"bytes32"}],"name":"ReserveLossArmed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"incidentId","type":"uint256"}],"name":"ReserveLossIncidentClosed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"incidentId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"armId","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"evidenceHash","type":"bytes32"}],"name":"ReserveLossIncidentOpened","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"curator","type":"address"},{"indexed":true,"internalType":"address","name":"backstop","type":"address"},{"indexed":true,"internalType":"address","name":"vault","type":"address"},{"indexed":false,"internalType":"address","name":"governor","type":"address"},{"indexed":false,"internalType":"address","name":"timelock","type":"address"}],"name":"ReserveLossModulesSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"armId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"incidentId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"approvedMaxLoss","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"actualLoss","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"evidenceHash","type":"bytes32"}],"name":"ReserveLossRatified","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"incidentId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"backingReduction","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"surplusAbsorbed","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"supplyReductionRequired","type":"uint256"}],"name":"ReserveLossRecognized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":false,"internalType":"uint256","name":"requested","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"credited","type":"uint256"}],"name":"USDCDeposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"USDCReleased","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"armId","type":"uint256"},{"indexed":true,"internalType":"bytes32","name":"evidenceHash","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"retainedPrincipalImpairment","type":"uint256"}],"name":"UnratifiedReserveLossArmCancelled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UPGRADE_INTERFACE_VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"accrualDelivery","outputs":[{"components":[{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"uint256","name":"senior","type":"uint256"},{"internalType":"uint256","name":"fee","type":"uint256"},{"internalType":"uint256","name":"effectiveSupply","type":"uint256"},{"internalType":"uint256","name":"backing","type":"uint256"},{"internalType":"uint256","name":"recognizedBacking","type":"uint256"},{"components":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"entryAssets","type":"uint256"},{"internalType":"uint256","name":"redemptionAssets","type":"uint256"},{"internalType":"uint256","name":"performanceAssets","type":"uint256"},{"internalType":"uint256","name":"feeAdjustedShares","type":"uint256"},{"internalType":"bool","name":"materializationAllowed","type":"bool"}],"internalType":"struct IContinuousAccrual.PricingState","name":"pricing","type":"tuple"},{"internalType":"address","name":"controller","type":"address"},{"internalType":"address","name":"vault","type":"address"},{"internalType":"address","name":"feeRecipient","type":"address"},{"internalType":"uint64","name":"accruedThrough","type":"uint64"},{"internalType":"uint8","name":"legs","type":"uint8"},{"internalType":"bool","name":"active","type":"bool"}],"internalType":"struct IContinuousAccrual.Delivery","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"kind","type":"uint8"},{"internalType":"bytes32","name":"identity","type":"bytes32"}],"name":"accrualExposure","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"}],"name":"accrualLoanScheduled","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"accrualMigration","outputs":[{"components":[{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"bytes32","name":"sessionKey","type":"bytes32"},{"internalType":"uint64","name":"cutoff","type":"uint64"},{"internalType":"uint32","name":"expected","type":"uint32"},{"internalType":"uint32","name":"imported","type":"uint32"},{"internalType":"uint256","name":"originalFace","type":"uint256"},{"internalType":"uint256","name":"importedOriginalFace","type":"uint256"},{"internalType":"uint256","name":"nextFacilityId","type":"uint256"},{"internalType":"bool","name":"active","type":"bool"}],"internalType":"struct IAccrualMigration.Progress","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"accrualModules","outputs":[{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"controller","type":"address"},{"internalType":"address","name":"vault","type":"address"},{"internalType":"address","name":"waterfall","type":"address"},{"internalType":"address","name":"bridge","type":"address"},{"internalType":"address","name":"registry","type":"address"},{"internalType":"address","name":"defaultManager","type":"address"}],"internalType":"struct IContinuousAccrual.Modules","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"accrualReservedExposure","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"accrualSnapshot","outputs":[{"components":[{"internalType":"uint256","name":"gross","type":"uint256"},{"internalType":"uint256","name":"unposted","type":"uint256"},{"internalType":"uint256","name":"unissued","type":"uint256"},{"internalType":"uint256","name":"seniorUnissued","type":"uint256"},{"internalType":"uint256","name":"feeUnissued","type":"uint256"},{"internalType":"address","name":"feeRecipient","type":"address"},{"internalType":"uint64","name":"accruedThrough","type":"uint64"},{"internalType":"bool","name":"enabled","type":"bool"},{"internalType":"bool","name":"fresh","type":"bool"}],"internalType":"struct IContinuousAccrual.Snapshot","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"}],"name":"accruedDebt","outputs":[{"components":[{"internalType":"uint256","name":"principal","type":"uint256"},{"internalType":"uint256","name":"interest","type":"uint256"},{"internalType":"uint256","name":"balanceCeiling","type":"uint256"},{"internalType":"uint64","name":"accruedThrough","type":"uint64"},{"internalType":"uint64","name":"nextCapitalization","type":"uint64"},{"internalType":"uint64","name":"maturity","type":"uint64"},{"internalType":"bool","name":"pik","type":"bool"},{"internalType":"bool","name":"active","type":"bool"},{"internalType":"bool","name":"known","type":"bool"}],"internalType":"struct IAccrualLifecycle.Debt","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"}],"name":"accruedInterestLegs","outputs":[{"components":[{"internalType":"uint256","name":"cash","type":"uint256"},{"internalType":"uint256","name":"pik","type":"uint256"},{"internalType":"uint64","name":"accruedThrough","type":"uint64"},{"internalType":"bool","name":"mixed","type":"bool"},{"internalType":"bool","name":"known","type":"bool"}],"internalType":"struct IAccrualLifecycle.InterestLegs","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"classId","type":"uint256"}],"name":"accruedPastDue","outputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"activeReserveLossIncident","outputs":[{"internalType":"uint256","name":"incidentId","type":"uint256"},{"internalType":"bytes32","name":"evidenceHash","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"},{"components":[{"internalType":"uint16","name":"rateBps","type":"uint16"},{"internalType":"uint32","name":"yearSeconds","type":"uint32"},{"internalType":"uint64","name":"nextPaymentDue","type":"uint64"},{"internalType":"uint64","name":"paymentInterval","type":"uint64"},{"internalType":"uint64","name":"maturity","type":"uint64"}],"internalType":"struct IAccrualLifecycle.Terms","name":"terms","type":"tuple"}],"name":"amendAccruingLoan","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"},{"components":[{"internalType":"uint16","name":"cashRateBps","type":"uint16"},{"internalType":"uint16","name":"pikRateBps","type":"uint16"},{"internalType":"uint32","name":"yearSeconds","type":"uint32"},{"internalType":"uint64","name":"nextPikCapitalization","type":"uint64"},{"internalType":"uint64","name":"pikCapitalizationInterval","type":"uint64"},{"internalType":"uint64","name":"maturity","type":"uint64"}],"internalType":"struct IAccrualLifecycle.MixedTerms","name":"terms","type":"tuple"}],"name":"amendMixedAccruingLoan","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"evidenceHash","type":"bytes32"}],"name":"armReserveLossFreeze","outputs":[{"internalType":"uint256","name":"armId","type":"uint256"},{"internalType":"uint256","name":"incidentId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"borrowerPayoutRegistry","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"expectedArmId","type":"uint256"},{"internalType":"bytes32","name":"evidenceHash","type":"bytes32"}],"name":"cancelAndDisable","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"expectedArmId","type":"uint256"},{"internalType":"bytes32","name":"evidenceHash","type":"bytes32"}],"name":"cancelUnratifiedArm","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"maximum","type":"uint256"}],"name":"checkpointAccrual","outputs":[{"internalType":"uint256","name":"processed","type":"uint256"},{"internalType":"bool","name":"fresh","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"incidentId","type":"uint256"}],"name":"closeReserveLossIncident","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"controller","type":"address"},{"internalType":"address","name":"vault","type":"address"},{"internalType":"address","name":"waterfall","type":"address"},{"internalType":"address","name":"bridge","type":"address"},{"internalType":"address","name":"registry","type":"address"},{"internalType":"address","name":"defaultManager","type":"address"}],"internalType":"struct IContinuousAccrual.Modules","name":"modules_","type":"tuple"}],"name":"configureContinuousAccrual","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"caller","type":"address"},{"internalType":"address","name":"from","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"consumeAccrualLossBurn","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"},{"internalType":"uint256","name":"loss","type":"uint256"}],"name":"consumeExitPrepayment","outputs":[{"internalType":"uint256","name":"used","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"armId","type":"uint256"},{"internalType":"bytes32","name":"evidenceHash","type":"bytes32"}],"name":"creditRecoveredIdleUSDC","outputs":[{"internalType":"uint256","name":"credited","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"curatorWithdrawalsLocked","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"custodyLossUnabsorbed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"name":"denormalizeUSDC","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"deployedPrincipal","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"}],"name":"deployedTo","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"depositUSDC","outputs":[{"internalType":"uint256","name":"credited","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"enableContinuousAccrual","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"enableMixedInterest","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"exitPrepaidAbsorption","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"expectedArmId","type":"uint256"},{"internalType":"bytes32","name":"evidenceHash","type":"bytes32"}],"name":"finalizeAndDisable","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"idleCustodyShortfall","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"idleReserve","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"idleUSDC","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"admin","type":"address"},{"internalType":"address","name":"reserveAdmin","type":"address"},{"internalType":"address","name":"guardian","type":"address"},{"internalType":"address","name":"upgrader","type":"address"},{"internalType":"address","name":"usdc_","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"lossAbsorber","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lossController","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"legs","type":"uint8"}],"name":"materializeAccrued","outputs":[{"internalType":"uint256","name":"senior","type":"uint256"},{"internalType":"uint256","name":"fee","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"mixedInterestEnabled","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"mixedInterestVersion","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"normalizeUSDC","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"observeIdleUSDC","outputs":[{"internalType":"uint256","name":"recorded","type":"uint256"},{"internalType":"uint256","name":"live","type":"uint256"},{"internalType":"uint256","name":"shortfall","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"incidentNonce","type":"uint256"},{"internalType":"bytes32","name":"evidenceHash","type":"bytes32"}],"name":"openReserveLossIncident","outputs":[{"internalType":"uint256","name":"incidentId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"}],"name":"postAccruedLoan","outputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"step","type":"bytes"}],"name":"prepareContinuousAccrualMigration","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"}],"name":"principalImpairmentOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"proxiableUUID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"expectedArmId","type":"uint256"},{"internalType":"bytes32","name":"evidenceHash","type":"bytes32"},{"internalType":"uint256","name":"approvedMaxLoss","type":"uint256"}],"name":"ratifyAndOpen","outputs":[{"internalType":"uint256","name":"incidentId","type":"uint256"},{"internalType":"uint256","name":"actualLoss","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"recapitalize","outputs":[{"internalType":"uint256","name":"credited","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes32","name":"evidenceHash","type":"bytes32"}],"name":"recognizePrincipalImpairment","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"recognizedBackingValue","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"recognizedReserveLoss","outputs":[{"internalType":"uint256","name":"backingReduction","type":"uint256"},{"internalType":"uint256","name":"surplusAbsorbed","type":"uint256"},{"internalType":"uint256","name":"supplyReductionRequired","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"reconcileIdleUSDC","outputs":[{"internalType":"uint256","name":"shortfall","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"usdcAmount","type":"uint256"}],"name":"recordDeployment","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"recordExitPrepayment","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"recordFeeCapitalization","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"},{"internalType":"address","name":"payer","type":"address"},{"internalType":"uint256","name":"usdcAmount","type":"uint256"},{"internalType":"uint256","name":"principal","type":"uint256"}],"name":"recordPayment","outputs":[{"internalType":"uint256","name":"receivedValue","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"recordPikCapitalization","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"recordPrincipalWritedown","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"}],"name":"registerAccruingLoan","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes32","name":"evidenceHash","type":"bytes32"}],"name":"releasePrincipalImpairment","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"releaseUSDC","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"callerConfirmation","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"},{"internalType":"address","name":"payer","type":"address"},{"internalType":"uint256","name":"principal","type":"uint256"},{"internalType":"uint256","name":"interest","type":"uint256"}],"name":"repayAccruingLoan","outputs":[{"internalType":"uint256","name":"outstanding","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"requireAccrualFresh","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[],"name":"requireAccrualIdle","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[],"name":"requireLegacyRollbackSafe","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[],"name":"reserveDeficit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"reserveLossArm","outputs":[{"internalType":"uint256","name":"armId","type":"uint256"},{"internalType":"uint256","name":"incidentId","type":"uint256"},{"internalType":"bytes32","name":"evidenceHash","type":"bytes32"},{"internalType":"bool","name":"armsEnabled","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"reserveLossExitsLocked","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"incidentId","type":"uint256"}],"name":"reserveLossIncidentUsed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"reserveLossModules","outputs":[{"internalType":"address","name":"curator","type":"address"},{"internalType":"address","name":"backstop","type":"address"},{"internalType":"address","name":"vault","type":"address"},{"internalType":"address","name":"governor","type":"address"},{"internalType":"address","name":"timelock","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"armId","type":"uint256"}],"name":"reserveLossRecoveryCapacity","outputs":[{"internalType":"uint256","name":"nativeUnits","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"evidenceHash","type":"bytes32"}],"name":"resolveReserveDeficit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"}],"name":"retireAccruedLoan","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"roundingLossUnabsorbed","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"}],"name":"serviceAccruedLoan","outputs":[{"internalType":"uint256","name":"capitalized","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint16","name":"feeBps","type":"uint16"},{"internalType":"address","name":"recipient","type":"address"}],"name":"setAccrualFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"},{"internalType":"bool","name":"marked","type":"bool"}],"name":"setAccrualPastDue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"registry","type":"address"}],"name":"setBorrowerPayoutRegistry","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"enabled","type":"bool"}],"name":"setGuardianReserveLossArmsEnabled","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"absorber","type":"address"}],"name":"setLossAbsorber","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"controller_","type":"address"}],"name":"setLossController","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"curator","type":"address"},{"internalType":"address","name":"backstop","type":"address"},{"internalType":"address","name":"vault","type":"address"},{"internalType":"address","name":"governor","type":"address"},{"internalType":"address","name":"timelock","type":"address"}],"name":"setReserveLossModules","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"}],"name":"stopAccruingLoan","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalBackingValue","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalPrincipalImpairment","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"facilityId","type":"uint256"}],"name":"unpostedAccruedLoan","outputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unrecordedUSDC","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"usdc","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"writeDownIdleUSDC","outputs":[],"stateMutability":"pure","type":"function"}],"is_changed_bytecode":false,"is_partially_verified":true,"constructor_args":null}