Skip to content
Verified contractExactBUSL-1.1

BridgeAccrualLib

Address0x736b3d9edb11842a04b0fb9a4ae71fc8183b68f6
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.30

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 100 runs
EVM version
cancun
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,459,358
Creation transaction
0xe72473fa07…73cca786c9

src/libraries/BridgeAccrualLib.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;

import {IContinuousAccrual, IAccrualToken} from "../interfaces/IContinuousAccrual.sol";
import {IMintRedeemController} from "../interfaces/IMintRedeemController.sol";
import {IReserveManager} from "../interfaces/IReserveManager.sol";

interface IMixedInterestVersion {
    function mixedInterestVersion() external pure returns (bytes32);
}

interface IMixedInterestReserve {
    function enableMixedInterest() external;
}

/// @title BridgeAccrualLib
/// @notice Fixed-ABI validation of the bridge's permanent continuous-accounting source.
/// @dev Linked calls execute in the bridge's context. The host authenticates governance and
///      writes its append-only reserve slot only after every read-only identity check succeeds.
library BridgeAccrualLib {
    bytes32 private constant _MIXED_INTEREST_VERSION = keccak256("forestroad.mixed-interest.v1");
    /// @notice A proposed source does not identify the bridge's existing native module routes.

    error BridgeAccrual_InvalidReserve(address reserve);

    /// @notice Validates the token-first binding and both controller and native waterfall routes.
    /// @param reserve The candidate accounting reserve proxy.
    /// @param registry The bridge's already configured collateral registry.
    /// @param oracle The bridge's already configured attestation oracle.
    function validate(address reserve, address registry, address oracle) public view {
        if (reserve.code.length == 0) revert BridgeAccrual_InvalidReserve(reserve);
        bytes memory data = _reply(reserve, abi.encodeCall(IContinuousAccrual.accrualModules, ()), 224, reserve);
        uint256[7] memory words = abi.decode(data, (uint256[7]));
        for (uint256 i; i < 7; ++i) {
            if (words[i] > type(uint160).max || address(uint160(words[i])).code.length == 0) {
                revert BridgeAccrual_InvalidReserve(reserve);
            }
        }
        IContinuousAccrual.Modules memory m = abi.decode(data, (IContinuousAccrual.Modules));
        if (m.bridge != address(this) || m.registry != registry) revert BridgeAccrual_InvalidReserve(reserve);
        data = _reply(m.token, abi.encodeCall(IAccrualToken.accrualReserve, ()), 32, reserve);
        if (abi.decode(data, (uint256)) != uint256(uint160(reserve))) revert BridgeAccrual_InvalidReserve(reserve);
        data = _reply(m.controller, abi.encodeCall(IMintRedeemController.modules, ()), 96, reserve);
        uint256[3] memory controller = abi.decode(data, (uint256[3]));
        if (
            controller[0] != uint256(uint160(m.token)) || controller[1] > type(uint160).max
                || controller[2] != uint256(uint160(reserve))
        ) revert BridgeAccrual_InvalidReserve(reserve);
        data = _reply(m.waterfall, abi.encodeWithSignature("modules()"), 192, reserve);
        uint256[6] memory waterfall = abi.decode(data, (uint256[6]));
        if (
            waterfall[0] != uint256(uint160(address(this))) || waterfall[1] != uint256(uint160(registry))
                || waterfall[2] != uint256(uint160(reserve)) || waterfall[3] != uint256(uint160(m.controller))
                || waterfall[4] != uint256(uint160(m.vault)) || waterfall[5] != uint256(uint160(oracle))
        ) revert BridgeAccrual_InvalidReserve(reserve);
        data = _reply(reserve, abi.encodeCall(IReserveManager.lossController, ()), 32, reserve);
        if (abi.decode(data, (uint256)) != uint256(uint160(m.controller))) revert BridgeAccrual_InvalidReserve(reserve);
    }

    /// @notice Requires the reserve and bound waterfall to implement the same mixed-interest ABI.
    function activateMixed(address reserve) public {
        _requireMixedVersion(reserve, reserve);
        bytes memory data = _reply(reserve, abi.encodeCall(IContinuousAccrual.accrualModules, ()), 224, reserve);
        IContinuousAccrual.Modules memory m = abi.decode(data, (IContinuousAccrual.Modules));
        if (m.bridge != address(this)) revert BridgeAccrual_InvalidReserve(reserve);
        _requireMixedVersion(m.waterfall, reserve);
        _requireMixedVersion(m.defaultManager, reserve);
        IMixedInterestReserve(reserve).enableMixedInterest();
    }

    /// @notice Prevents a post-activation bridge downgrade to an implementation that cannot decode mixed state.
    function validateMixedImplementation(address implementation) public view {
        _requireMixedVersion(implementation, implementation);
    }

    function _requireMixedVersion(address target, address reported) private view {
        bytes memory data = _reply(target, abi.encodeCall(IMixedInterestVersion.mixedInterestVersion, ()), 32, reported);
        if (abi.decode(data, (bytes32)) != _MIXED_INTEREST_VERSION) {
            revert BridgeAccrual_InvalidReserve(reported);
        }
    }

    /// @dev Reject failed or malformed probes before decoding; no unchecked external result remains.
    function _reply(address target, bytes memory request, uint256 length, address reserve)
        private
        view
        returns (bytes memory data)
    {
        bool ok;
        (ok, data) = target.staticcall(request);
        if (!ok || data.length != length) revert BridgeAccrual_InvalidReserve(reserve);
    }
}

src/interfaces/IContinuousAccrual.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;

/// @title IContinuousAccrual
/// @notice Reserve-owned accounting and exact delivery of previously accrued interest.
/// @dev Separate from the legacy reserve interface so activation is explicit. Amounts are
///      normalized to 18 decimals. Delivery changes physical balances, never economic ownership.
interface IContinuousAccrual {
    /// @notice Modules bound to one independently backed chain instance.
    /// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
    struct Modules {
        address token;
        address controller;
        address vault;
        address waterfall;
        address bridge;
        address registry;
        address defaultManager;
    }

    /// @notice Constant-time accounting, capped at the first unprocessed schedule boundary.
    /// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
    struct Snapshot {
        uint256 gross;
        uint256 unposted;
        uint256 unissued;
        uint256 seniorUnissued;
        uint256 feeUnissued;
        address feeRecipient;
        uint64 accruedThrough;
        bool enabled;
        bool fresh;
    }

    /// @notice Vault-computed prices and permission for a neutral physical delivery.
    /// @dev entryAssets includes any unvested assets; assets is the ordinary share-price base.
    /// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
    struct PricingState {
        uint256 assets;
        uint256 entryAssets;
        uint256 redemptionAssets;
        uint256 performanceAssets;
        uint256 feeAdjustedShares;
        bool materializationAllowed;
    }

    /// @notice One immutable, same-transaction permit and coherent public price snapshot.
    /// @dev Unselected amounts are zero. A zero/default inactive record grants no authority.
    /// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
    struct Delivery {
        uint256 nonce;
        uint256 senior;
        uint256 fee;
        uint256 effectiveSupply;
        uint256 backing;
        uint256 recognizedBacking;
        PricingState pricing;
        address controller;
        address vault;
        address feeRecipient;
        uint64 accruedThrough;
        uint8 legs;
        bool active;
    }

    /// @notice Reads the configured module identities, including before activation.
    function accrualModules() external view returns (Modules memory);

    /// @notice Reads recognized income and its outstanding physical posting/issuance.
    function accrualSnapshot() external view returns (Snapshot memory);

    /// @notice Reads the current delivery permit, or an inactive default record.
    function accrualDelivery() external view returns (Delivery memory);

    /// @notice Refuses a price-sensitive write at an unresolved accrual boundary or operation.
    function requireAccrualFresh() external view;

    /// @notice Delivers selected existing claims: senior=1, fee=2, both=3.
    /// @dev No amount, destination, timestamp or fee rate is supplied by the caller.
    function materializeAccrued(uint8 legs) external returns (uint256 senior, uint256 fee);
}

/// @notice Token continuation accepting only the bound reserve's current exact permit.
interface IAccrualToken {
    /// @notice The immutable-once-configured accounting reserve, or zero before binding.
    function accrualReserve() external view returns (address);

    /// @notice Mints the selected legs of one unused, active delivery permit.
    function mintAccrued(uint256 nonce) external;
}

/// @notice Controller continuation, callable only by its configured reserve.
interface IAccrualController {
    /// @notice Relays one exact reserve-owned delivery permit to the token.
    function mintAccrued(uint256 nonce) external;
}

/// @notice Vault views needed to admit a neutral delivery without a guarded write callback.
interface IAccrualVault {
    /// @notice The immutable-once-configured accounting reserve, or zero before binding.
    function accrualReserve() external view returns (address);

    /// @notice Supplies a coherent price snapshot and current delivery admission state.
    function accrualPricingState() external view returns (IContinuousAccrual.PricingState memory);
}

/// @title IReliefPricingCache
/// @notice Optional exact-discount preparation; it grants no financial authority.
interface IReliefPricingCache {
    /// @notice Derives reusable discounts from current protocol state, without caller-supplied values.
    function prepareReliefPricing() external;
}

src/interfaces/IMintRedeemController.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;

/// @notice The one-bit pause surface of a wired module, declared here because `previewRedeem` must
///         read the reserve's pause and `IReserveManager` does not declare it.
/// @dev CANTINA 3.1.3 LIMB (a), CLOSED BY CONSTRUCTION ON THIS INSTANCE. On Ethereum the quote read
///      the controller pause and the token pause but not the reserve's, so it could publish a full
///      price for a redemption whose every release is `whenNotPaused`. The disposition there was
///      "an integrator should read `ReserveManager.paused()` alongside the quote", because closing
///      it was an upgrade. The mechanical reason the sibling fix missed the third surface is that
///      `ReserveManager` gets `paused()` from `PausableUpgradeable` and never declares it on its own
///      interface, so nothing in the type system pointed at it. This declaration is that pointer.
interface IPausableModule {
    /// @notice True while the module refuses its `whenNotPaused` entry points.
    function paused() external view returns (bool);
}

/// @title IMintRedeemController
/// @notice KYC-gated issuance and redemption of USDfr against canonical USDC, and the enforcement
///         point of the protocol's solvency rule. MINT is at par and is CLOSED while the protocol
///         is under-backed. REDEMPTION is at par while the protocol is whole; while it is short it
///         settles at the JUNIOR-DRAWN price, which is at least the coverage ratio and MAY BE PAR,
///         and which the caller must elect via `redeem(uint256,uint256)`.
///         AUDIT FIX (SWEEP-2 S2-I1) — THIS FILE-LEVEL LINE SAID "at the coverage ratio while it is
///         short", the THIRD round in which a false settlement claim sat on the one line an
///         explorer or ABI doc renders first. SWEEP-1 MRC-F2 corrected the two `redeem` overloads
///         and the contract-level block and left this headline. Falsified by the shipped
///         `ADR0034Y_AtomicJuniorExitDraw::test_Y_theExitSettlesAtParWhileCuratorCapitalStandsIntact`
///         and by SWEEP-2 S2-F3, in which a sub-par book settled at PAR because ADR-0034 Y-bis drew
///         junior capital forward to fund it.
/// @dev THE SOLVENCY RULE IS NOT ADR-0012's ABSOLUTE PREDICATE ANY MORE, AND THIS HEADLINE USED TO
///      SAY IT WAS (corrected in audit round R18). Until R18 this contract-level notice line read "KYC-gated 1:1
///      mint/redeem … `USDfr.totalSupply() <= backingValue()` after every supply-affecting op".
///      Both halves were false of the shipped code, and an auditor handed ADR-0012 plus this
///      interface as the specification would reasonably have reported "the contract does not
///      enforce its stated invariant" as a High. What the contract actually enforces:
///        - Redemption is NOT 1:1. R16-M3 made the exit price `backing / supply` while short, and
///          R17 gave the one-argument form a PAR FLOOR, so it reverts rather than settling short.
///        - The absolute predicate was REPLACED by the NON-WORSENING rule: an operation may not
///          increase `deficit = max(0, totalSupply - backingValue)`. While the protocol is whole
///          that reduces exactly to ADR-0012 and still reverts with
///          `Controller_BackingInvariantViolated`; while it is short it permits the operations that
///          repair holders' position and refuses the ones that dilute it. See
///          `MintRedeemController`'s contract-level NatSpec, which sets out the whole model.
///        - It is not asserted "after every supply-affecting op": `burnLoss` carries NO solvency
///          assertion, deliberately (finding M6 — the assertion it used to carry was unfalsifiable).
///      The comment was not independently wrong: it correctly quoted `ADR/0012-backing-invariant.md`
///      (Status: Accepted), which still states the superseded absolute rule verbatim as "a hard
///      on-chain check on every supply-affecting operation". THAT ADR MUST BE AMENDED OR SUPERSEDED
///      so the code and the decision record agree; it is OUTSTANDING and is Forest Road's to take
///      (CLAUDE.md §0.7).
interface IMintRedeemController {
    // ── Events ───────────────────────────────────────────────────────────
    event Minted(address indexed user, uint256 usdcIn, uint256 usdfrOut);
    event Redeemed(address indexed user, uint256 usdfrIn, uint256 usdcOut);
    /// @notice Emitted when USDfr is minted against attested yield receipts (waterfall path).
    event YieldMinted(address indexed to, uint256 amount);
    /// @notice Emitted when USDfr is burned to realize a loss (cascade layer 3).
    event LossBurned(address indexed from, uint256 amount);
    /// @notice AUDIT FIX (R16-M3). Emitted IN ADDITION to `Redeemed` when a redemption settled
    ///         below par because the protocol was under-backed. Carries the supply and backing
    ///         the quote was struck against, so the coverage ratio applied to any exit is
    ///         reconstructable purely from events (CLAUDE.md §3.1).
    /// @param user The redeemer.
    /// @param usdfrBurned USDfr burned (whole-USDC-unit aligned).
    /// @param usdcOut Native USDC units actually paid out.
    /// @param supply `totalUSDfr()` before the redemption.
    /// @param backing `backingValue()` before the redemption.
    event SubParRedemption(address indexed user, uint256 usdfrBurned, uint256 usdcOut, uint256 supply, uint256 backing);
    /// @notice AUDIT FIX (R17). Emitted alongside `SubParRedemption`. Records the value
    ///         PERMANENTLY crystallised out of the senior layer by an exit priced against a
    ///         REVERSIBLE impairment mark, and the running total. `mintableHeadroom()` nets the
    ///         running total out, so value recovered when the mark is released stays in the pool
    ///         as coverage instead of being minted to the `sUSDfr` vault as yield.
    /// @param user The redeemer who bore it.
    /// @param amount `usdfrBurned - usdcOut * 1e12` for this exit, in 18-decimal USD.
    /// @param cumulative `seniorSubParShortfall()` after this exit.
    event SeniorShortfallCrystallised(address indexed user, uint256 amount, uint256 cumulative);
    /// @notice AUDIT FIX (R16-M1). Governance authorized or revoked a `mintYield` destination.
    event YieldSinkUpdated(address indexed account, bool authorized);
    /// @notice AUDIT FIX (R16-M1/M2). Governance authorized or revoked a `burnLoss` source.
    event LossSourceUpdated(address indexed account, bool authorized);

    // ── Errors ───────────────────────────────────────────────────────────
    error Controller_NotKYCAllowed(address account);
    error Controller_BackingInvariantViolated(uint256 supply, uint256 backing);
    error Controller_ZeroAmount();
    error Controller_AmountTooSmall(uint256 usdfrAmount);

    /// @notice An unratified arm refused a direct redemption.
    /// @param armId Active custody arm.
    /// @param usdcOut Proposed settlement in native USDC units.
    /// @param usdfrIn USDfr claims proposed for redemption.
    error Controller_ReserveLossArmFreeze(uint256 armId, uint256 usdcOut, uint256 usdfrIn);

    /// @notice The redemption would have burned more USDfr than the post-draw supply.
    /// @dev CANTINA 3.1.1, RE-DERIVED AT SCALE 1 AND CLOSED RATHER THAN ACKNOWLEDGED. On Ethereum
    ///      the whole-unit grid returned `M mod 1e12` wei of headroom at the top of the range, so
    ///      `usdfrIn + drawn` overflowed only for inputs within 1e12 of `type(uint256).max` - a
    ///      panic window of width at most 2**40, which is why "acknowledged" was a defensible
    ///      judgement. At scale 1 the grid is the identity, `usdfrIn == usdfrAmount` exactly, and
    ///      the window widens to the whole top `drawn` of the range. That is not the same judgement
    ///      about the same object. Bounding the SUM rather than the addend makes the overflow
    ///      UNREPRESENTABLE rather than merely unlikely, refuses only inputs no holder can hold, and
    ///      makes `previewRedeem` answer a controller error instead of `Panic(0x11)`.
    /// @param usdfrIn The amount the exit would burn.
    /// @param bound `supply - drawn`, which `supply - drawn <= supply` makes underflow-free because
    ///        `drawn` was burned out of `supply`.
    error Controller_RedeemExceedsSupply(uint256 usdfrIn, uint256 bound);
    /// @notice AUDIT FIX (R4-01): the user par paths are closed while the reserve holds less USDC
    ///         than its idle ledger claims. Recognition of the gap is permissionless and immediate;
    ///         restoring custody, or the authenticated custody-loss cascade writing the ledger down
    ///         to the live balance, reopens mint and redeem with no governance action.
    /// @param shortfallValue The observable custody gap in 18-decimal USD.
    /// @param recognizedBacking Backing net of that gap — the honest basis.
    error Controller_ReserveCustodyShortfall(uint256 shortfallValue, uint256 recognizedBacking);

    /// @notice AUDIT FIX (R16-M3/M4/M5). The operation would have WIDENED an already-standing
    ///         backing deficit. Distinct from `Controller_BackingInvariantViolated`, which is
    ///         raised when a whole protocol would be pushed below par: an integrator seeing that
    ///         error inside a knowingly sub-par protocol would reasonably read it as the standing
    ///         condition rather than as a refusal of this specific call.
    /// @param deficitBefore `max(0, totalUSDfr() - backingValue())` before the operation.
    /// @param deficitAfter The same quantity after it, which must not exceed `deficitBefore`.
    error Controller_DeficitWorsened(uint256 deficitBefore, uint256 deficitAfter);

    /// @notice A paired-yield baseline is already open, so a second cannot be started.
    error Controller_PairedYieldAlreadyOpen(address caller);
    /// @notice A split mint must consume this caller's existing paired backing baseline.
    error Controller_PairedYieldRequired();
    /// @notice A paired operation cannot complete against a changed retention obligation.
    error Controller_PairedRetentionChanged(uint256 beforeRequirement, uint256 afterRequirement);
    /// @notice The protocol fee cannot exceed the total amount being issued.
    error Controller_InvalidYieldSplit(uint256 total, uint256 fee);

    /// @notice A paired-yield baseline was recorded before its caller moved backing.
    event PairedYieldOpened(address indexed caller, uint256 supplyBefore, uint256 backingBefore);

    /// @notice A stranded paired-yield baseline was cleared by governance.
    event PairedYieldCleared(address indexed caller);

    /// @notice Records the supply/backing baseline for a yield mint whose backing leg moves first.
    function beginPairedYield() external;

    /// @notice Governance escape for a paired-yield baseline stranded by a reverted operation.
    function clearStalePairedYield() external;

    /// @notice AUDIT FIX (R16-M3). Par issuance is closed while the protocol is under-backed for
    ///         ANY reason — a G3 conservative mark or a residual cascade deficit as well as the
    ///         R4-01 custody gap. `redeem` deliberately stays OPEN in this state and re-prices to
    ///         the coverage ratio; see `previewRedeem`.
    /// @param supply `totalUSDfr()` at the time of refusal.
    /// @param backing `backingValue()` at the time of refusal.
    error Controller_MintClosedWhileUnderBacked(uint256 supply, uint256 backing);

    /// @notice AUDIT FIX (R16-L2). The USDC the user was charged did not arrive in the reserve's
    ///         custody, or the reserve credited a value that does not match it. Measured from the
    ///         reserve's own token balance rather than from anything the reserve reports about
    ///         itself, so `mint` no longer derives both sides of its safety check from one module.
    /// @param requested Native USDC units pulled from the user.
    /// @param delivered The reserve's measured USDC balance increase.
    /// @param credited The 18-decimal value `depositUSDC` reported.
    error Controller_DepositNotCustodied(uint256 requested, uint256 delivered, uint256 credited);

    /// @notice AUDIT FIX (R16-M1). `to` is not a governance-authorized yield destination.
    error Controller_NotYieldSink(address to);

    /// @notice AUDIT FIX (R16-M1/M2). `from` is not a governance-authorized loss source. Without
    ///         this, `burnLoss` and `mintYield` composed into arbitrary confiscation, and
    ///         `USDfr.burn`'s allowance-free burn made any holder seizable one-sidedly.
    error Controller_NotLossSource(address from);

    /// @notice AUDIT FIX (R17). A loss source must be a CONTRACT. `burnLoss` burns with no
    ///         allowance, carries no backing assertion and is deliberately not pausable, so
    ///         listing an EOA would restore finding M2 — a forced, non-pro-rata seizure of one
    ///         named holder — in a single routine-looking timelock transaction. Mirrors
    ///         `ReserveManager.setLossAbsorber`/`setLossController`. Deliberately NOT applied to
    ///         `setYieldSink`, whose fee-recipient treasury may legitimately be an EOA.
    error Controller_LossSourceNotContract(address account);

    /// @notice AUDIT FIX (R17). The settled price was below the floor the caller named. The
    ///         one-argument `redeem` supplies the PAR floor, so it reverts with this rather than
    ///         silently haircutting a holder against a mark that may later be released.
    /// @param usdcOut What the redemption would have paid.
    /// @param minUsdcOut The floor the caller required.
    error Controller_SlippageExceeded(uint256 usdcOut, uint256 minUsdcOut);

    /// @notice AUDIT FIX (R17). Backing has fallen to zero, so there is nothing to pay out at any
    ///         size. Previously this answered `Controller_AmountTooSmall`, which told the holder
    ///         their amount was the problem when the truth was that the protocol was worth nothing.
    /// @param supply `totalUSDfr()` at the time of refusal.
    error Controller_NoRedeemableBacking(uint256 supply);

    /// @notice AUDIT FIX (R17). The USDC the redemption was priced at did not reach the redeemer.
    ///         The outflow twin of `Controller_DepositNotCustodied`: R16-L2 installed an
    ///         independent measurement on the inflow leg only, leaving `redeem` to take the
    ///         reserve's own word for a release on the leg where the holder's USDfr is already
    ///         burned and the loss is irreversible.
    /// @param expected The quoted payout in native USDC units.
    /// @param settled The redeemer's measured USDC balance increase.
    /// @param usdfrBurned The USDfr burned to pay for it.
    error Controller_RedemptionNotSettled(uint256 expected, uint256 settled, uint256 usdfrBurned);

    /// @notice AUDIT FIX (R17). USDC was left sitting on the controller after a mint. The
    ///         controller is value-neutral at rest; a reserve that funded the deposit from
    ///         somewhere other than the controller's allowance satisfies the delivery equality
    ///         while leaving the user's cash here with a live approval against it.
    /// @dev Measured as a DELTA across the call, never as an absolute balance: anyone can send
    ///      USDC to the controller, so `balanceOf(this) != 0` would be a one-wei permanent
    ///      griefing lock on `mint`.
    /// @param balanceBefore The controller's USDC balance before the deposit leg.
    /// @param balanceAfter Its balance after it. Any inequality is refused.
    error Controller_CashStrandedOnController(uint256 balanceBefore, uint256 balanceAfter);

    /// @notice AUDIT FIX (R17). The operation would have widened the deficit measured on the
    ///         RECOGNITION-AWARE basis — backing net of the custody shortfall the reserve can
    ///         observe right now. Raised only by `mintYield`, the one supply-EXPANDING path with
    ///         no custody precondition; `mint` and `redeem` are refused earlier by
    ///         `Controller_ReserveCustodyShortfall`, and `burnLoss` is deliberately ungated.
    /// @param deficitBefore `max(0, totalUSDfr() - recognizedBackingValue())` before the call.
    /// @param deficitAfter The same quantity after it.
    error Controller_RecognizedDeficitWorsened(uint256 deficitBefore, uint256 deficitAfter);

    /// @notice AUDIT FIX (R17). A yield mint would have consumed value retained against
    ///         `seniorSubParShortfall()` — the haircut crystallised out of holders who exited
    ///         against a REVERSIBLE impairment mark. `mintableHeadroom()` advertises the retention;
    ///         this error enforces it.
    /// @dev CORRECTED (SWEEP-1 MRC-F3, 2026-08-08). This sentence used to end "...because
    ///      `WaterfallEngine.fund`'s origination-fee mint is not sized off that headroom and would
    ///      otherwise spend it." THAT JUSTIFICATION EXPIRED AT R18. `WaterfallEngine.fund` now
    ///      reads `uint256 headroom = $.controller.mintableHeadroom();` and clamps
    ///      `mintable = fee <= headroom ? fee : headroom` (WaterfallEngine.sol:195-197);
    ///      `MintRedeemController` says so in two places, and
    ///      `test_R18_A1_originationSurvivesACrystallisedHaircut` passes over the clamped path.
    ///      This is the same class of defect the merge author fixed on
    ///      `CollateralRegistry.conservativeSeniorMark`: a stale justification on a value path is
    ///      a defect, because the next engineer prunes the guard once they discover the reason
    ///      given for it is untrue.
    ///
    ///      THE ERROR IS STILL LOAD-BEARING, ON A DIFFERENT GROUND — DO NOT DELETE IT. It is the
    ///      LAST line of defence rather than the only one. `CREDIT_ROLE` gates `mintYield`, and
    ///      `Deploy.s.sol` grants that role to `WaterfallEngine` alone TODAY; a second grantee, or
    ///      any future unclamped call site, would spend the junior retention silently. The clamp is
    ///      a caller-side property; this is the callee-side one.
    /// @param threshold THE BOUND THAT WAS ACTUALLY ENFORCED, which differs by branch and is why
    ///        this parameter is not named `retention`. On an ordinary yield mint it is
    ///        `seniorSubParShortfall()`, the junior retention the surplus must not fall below. On a
    ///        PAIRED mint opened by `beginPairedYield` it is the surplus recorded BEFORE the caller
    ///        moved any backing, because a paired move raises backing and supply by the identical
    ///        amount and the property enforced there is exact neutrality rather than a floor.
    ///        Reporting the retention on the paired branch made the error describe a rule that
    ///        branch does not apply; corrected 2026-09-10.
    /// @param surplus `max(0, recognizedBackingValue() - totalUSDfr())` after the mint.
    error Controller_SeniorRetentionBreached(uint256 threshold, uint256 surplus);

    /// @notice AUDIT FIX (R18). The reserve took the USDC and reported the right credit but did not
    ///         BOOK it as backing. The recognition twin of `Controller_DepositNotCustodied`: R16-L2
    ///         measured custody and R17 measured the reported credit, while recognition was left to
    ///         the NON-WORSENING deficit rule — which a standing surplus silently pays for, up to
    ///         its own size. Measured as a DELTA on `backingValue()` across the deposit leg, so no
    ///         surplus can absorb it, and as an EQUALITY, so an over-booking reserve is refused too.
    /// @param credited The 18-decimal value `depositUSDC` reported.
    /// @param recognized The measured increase in `backingValue()` across the same call.
    error Controller_DepositNotRecognized(uint256 credited, uint256 recognized);

    /// @notice AUDIT FIX (R18). A loss source must not be an EIP-7702 DELEGATED EOA. Since Pectra
    ///         an ordinary key-controlled wallet that signed a delegation carries a 23-byte
    ///         `0xef0100`-prefixed code field, so `EXTCODESIZE` returns 23 and
    ///         `Controller_LossSourceNotContract`'s check admitted it — leaving finding M2 (a
    ///         forced, allowance-free, non-pro-rata seizure of one named holder, unstoppable by the
    ///         guardian) one routine-looking timelock transaction away for exactly the class of
    ///         wallet the guard claimed to exclude.
    error Controller_LossSourceIsDelegatedEOA(address account);

    /// @notice AUDIT FIX (R18). A composite view was read while this contract's reentrancy guard
    ///         was entered — i.e. from inside a supply change that has not finished settling — and
    ///         would have answered a number known to be false.
    /// @dev `_redeem` burns before it releases, and `DefaultManager.realizeLoss` burns before it
    ///      writes backing down; `USDfr._update` fires the participation-points hook inside every
    ///      one of those burns. From there `mintableHeadroom()` read the entire realised loss of a
    ///      cascade as distributable yield capacity, `backingInvariantHolds()` read TRUE on a short
    ///      book and `previewRedeem` quoted PAR on it. Reverting is the honest answer and is
    ///      fail-closed for an integrator; returning the number is the R4-01 self-contradiction one
    ///      frame deeper. The raw delegating views (`backingValue`, `recognizedBackingValue`,
    ///      `totalUSDfr`) are NOT gated: each is true whenever it is read. Only the composites are.
    error Controller_ViewUnavailableMidTransition();

    /// @notice `redeem(uint256,uint256,uint256)` was included after the caller's deadline
    ///         (ADR-0034 W).
    error Controller_DeadlinePassed(uint256 deadline, uint256 nowTimestamp);
    /// @notice The junior-draw source named by `ReserveManager.lossAbsorber()` is not on the
    ///         governance-maintained `setLossSource` list (ADR-0034 Y-bis). Fail-closed: the exit
    ///         refuses rather than burning a third party's USDfr on an unvouched-for pointer.
    error Controller_ExitDrawSourceNotAuthorised(address source);
    /// @notice The junior-draw source reported one number and moved another, or delivered more
    ///         than was asked of it (ADR-0034 Y-bis). Measured, not trusted.
    error Controller_ExitDrawNotDelivered(uint256 requested, uint256 reported, uint256 measured);

    /// @notice Junior capital was drawn forward, in cascade order, to fund this exit's price
    ///         (ADR-0034 Y-bis). `drawn` USDfr was burned out of the junior layers.
    event SeniorExitJuniorDrawn(address indexed redeemer, uint256 required, uint256 drawn);

    // ── User paths (KYC-gated) ───────────────────────────────────────────
    /// @notice Deposits USDC (6 decimals) and mints USDfr 1:1 in 18-decimal USD units.
    function mint(uint256 usdcAmount) external returns (uint256 usdfrOut);

    /// @notice Burns USDfr and releases the reserve's cash equivalent AT PAR. While the protocol
    ///         is short this form settles at par out of JUNIOR capital drawn forward in the same
    ///         transaction (ADR-0034 Y-bis), and reverts `Controller_SlippageExceeded` only once
    ///         that draw cannot reach par. It never haircuts the caller. Use
    ///         `redeem(uint256,uint256)` to elect a sub-par exit.
    /// @dev AUDIT FIX (R18) CORRECTED THE NOTICE LINE ABOVE, which every block explorer, ABI
    ///      doc and integrator reads first. It said this form is "priced at the coverage ratio: par
    ///      while the protocol is whole, `backing / supply` while it is short". After R17's par
    ///      floor that is false of THIS form. The coverage-ratio behaviour described below is
    ///      R16-M3's and is true of the two-argument form.
    /// @dev CORRECTED AGAIN (SWEEP-1 MRC-F2, 2026-08-08) — SAME LINE, ONE ROUND LATER. R18's
    ///      replacement said this form "REVERTS" while short, full stop. That stopped being true
    ///      at ADR-0034 Y-bis, which draws curator first-loss and the sGROVE backstop forward in
    ///      the same transaction to fund the cascade-ordered price. MEASURED: with a gross quote of
    ///      185,928.705440 USDC this form settled 200,000.000000 — AT PAR, out of junior capital.
    ///      It reverts only when the draw cannot reach par. Two successive rounds put a false
    ///      settlement claim on the one line integrators read first; check it against
    ///      `MintRedeemController._quoteRedeem` and `_drawJuniorForExit` before editing it again.
    /// @dev AUDIT FIX (R17): THIS FORM SUPPLIES THE PAR FLOOR. It settles at par or reverts with
    ///      `Controller_SlippageExceeded`. R16 made the price a live function of state and left
    ///      this one-argument signature accepting whatever the ratio was at inclusion, while
    ///      several NON-timelocked paths move backing down in the same block. Taking a haircut is
    ///      now an explicit election: quote with `previewRedeem`, then call the two-argument form
    ///      with the floor you will accept.
    function redeem(uint256 usdfrAmount) external returns (uint256 usdcOut);

    /// @notice Burns USDfr and releases the reserve's cash equivalent, refusing to settle below
    ///         `minUsdcOut`. This is the form that accepts a SUB-PAR exit — an explicit, informed
    ///         election by the holder (R16-M3, R17).
    /// @dev CORRECTED (SWEEP-1 MRC-F2, 2026-08-08). This line said the form "pays the COVERAGE
    ///      RATIO". It pays the JUNIOR-DRAWN price, which is >= the coverage ratio and may be par:
    ///      ADR-0034 Y-bis draws curator first-loss and the sGROVE backstop forward in the same
    ///      transaction, and the gross `backing / supply` mark is only the floor the price degrades
    ///      to once junior capital is exhausted. Quote with `previewRedeem`, which shares the
    ///      drawn arithmetic.
    /// @dev AUDIT FIX (R17). `previewRedeem` is advisory ACROSS TRANSACTIONS — it shares
    ///      `redeem`'s arithmetic, not its state — so this parameter is the only thing that binds
    ///      the settlement price. Pass the value `previewRedeem` returned (or lower, to tolerate
    ///      movement).
    /// @dev THE DEADLINE IS NOW SHIPPED, ON A NEW SIGNATURE (ADR-0034 W). R17 wrote here that
    ///      "there is no deadline parameter: there is no AMM-style path here, and the floor alone
    ///      is sufficient to make the exit refusable", which argued an ACCEPTED requirement away.
    ///      `redeem(uint256,uint256,uint256)` carries it. THIS form is deliberately left
    ///      deadline-free rather than being given a new expiry semantic under an unchanged
    ///      signature — see that overload's NatSpec. Prefer the three-argument form.
    /// @param usdfrAmount USDfr offered; the burn is snapped down to the whole-USDC-unit grid.
    /// @param minUsdcOut The lowest native-USDC payout the caller will accept. Zero accepts ANY
    ///        price, including a deep haircut — pass zero only deliberately.
    function redeem(uint256 usdfrAmount, uint256 minUsdcOut) external returns (uint256 usdcOut);

    /// @notice Burns USDfr and releases the reserve's cash equivalent, refusing to settle below
    ///         `minUsdcOut` or after `deadline`. THE CANONICAL EXIT (ADR-0034 W).
    /// @dev A minimum-out bounds the PRICE; it does not bound WHEN the exit executes. Every path
    ///      that moves the coverage ratio down is un-timelocked and publicly visible before it
    ///      lands, so a transaction left in the mempool is a free option for whoever chooses
    ///      inclusion. See the implementation NatSpec.
    /// @param usdfrAmount USDfr offered; the burn is snapped down to the whole-USDC-unit grid.
    /// @param minUsdcOut The lowest native-USDC payout the caller will accept.
    /// @param deadline Latest `block.timestamp` at which this exit may settle.
    function redeem(uint256 usdfrAmount, uint256 minUsdcOut, uint256 deadline) external returns (uint256 usdcOut);

    // ── Protocol paths (credit layer; wired in Phases E/G) ───────────────
    /// @notice Mints USDfr to `to` against newly received, attested backing (loan
    ///         interest / reserve yield). `CREDIT_ROLE`.
    /// @dev AUDIT FIX (R16-M1): `to` must be a governance-authorized yield sink. Refuses while
    ///      the protocol is under-backed (incoming cash repairs the hole before it is paid out
    ///      as yield) and while the controller is paused (a pause must never permit supply
    ///      expansion). Callers should size the mint with `mintableHeadroom()`.
    /// @dev AUDIT FIX (R17/R18): it ALSO refuses while the surplus is below
    ///      `seniorSubParShortfall()` (`Controller_SeniorRetentionBreached`) — an ABSOLUTE level
    ///      check that bites in states the protocol publishes as fully backed. EVERY CALLER MUST
    ///      SIZE ITSELF OFF `mintableHeadroom()`: it is the one view that nets the retention, both
    ///      pauses and the recognition basis. `WaterfallEngine` now does so on BOTH of its mints
    ///      (interest since R16-M5, the origination fee since R18); a caller that does not will
    ///      revert rather than withhold.
    function mintYield(address to, uint256 amount) external;

    /// @notice Issues one paired increase to two authorized sinks, checking the complete total.
    /// @param senior Destination of total minus fee; unused when that amount is zero.
    /// @param total Total new supply, justified by the backing increase since beginPairedYield.
    /// @param feeRecipient Destination of fee; unused when fee is zero.
    /// @param fee Part of total allocated before the senior leg, in normalized USDfr units.
    function mintYieldSplit(address senior, uint256 total, address feeRecipient, uint256 fee) external;

    /// @notice Burns USDfr from `from` to realize a loss through the cascade.
    ///         `LOSS_BURNER_ROLE` — deliberately NOT `CREDIT_ROLE`.
    /// @dev AUDIT FIX (R16-M1/M2): `from` must be a governance-authorized loss source, and the
    ///      role is split from `CREDIT_ROLE` so `WaterfallEngine`, which never burns, no longer
    ///      holds the power to. Never pausable: loss absorption must stay available.
    function burnLoss(address from, uint256 amount) external;

    // ── Governance: credit-layer endpoints (AUDIT FIX R16-M1) ────────────
    /// @notice Authorizes (or revokes) an address as a destination for `mintYield`.
    function setYieldSink(address account, bool authorized) external;

    /// @notice Authorizes (or revokes) an address as a source for `burnLoss`.
    function setLossSource(address account, bool authorized) external;

    // ── Views ────────────────────────────────────────────────────────────
    /// @notice Current backing value on the RECORDED-LEDGER basis
    ///         (delegates to `ReserveManager.totalBackingValue()`).
    /// @dev AUDIT FIX (R4-01): this is the basis the C-01 custody-loss arithmetic reconciles
    ///      against within a single transaction and is deliberately NOT recognition-aware. For any
    ///      solvency or exit-pricing question use `recognizedBackingValue()`.
    function backingValue() external view returns (uint256);

    /// @notice AUDIT FIX (R4-01). Backing net of the custody shortfall the reserve can observe
    ///         right now (delegates to `ReserveManager.recognizedBackingValue()`).
    function recognizedBackingValue() external view returns (uint256);

    /// @notice Current USDfr total supply.
    function totalUSDfr() external view returns (uint256);

    /// @notice True if supply is covered on the RECORDED ledger.
    /// @dev Compatibility diagnostic only. DELIBERATELY BLIND TO THE CUSTODY SHORTFALL and no
    ///      longer consumed by `WaterfallEngine.distribute`: that path enforces exact receipt and
    ///      a non-worsening recognised deficit. Do not use this absolute view as an admission
    ///      gate, user-path condition, exit price, or solvency display.
    function creditServicingBackingHolds() external view returns (bool);

    /// @notice True if the backing invariant currently holds. Public so anyone can check.
    /// @dev AUDIT FIX (R4-01): measured against `recognizedBackingValue()`, so it can no longer
    ///      report true in the same block in which `observeIdleUSDC()` publishes a shortfall.
    /// @dev AUDIT FIX (R18): reverts with `Controller_ViewUnavailableMidTransition` if called from
    ///      inside an unsettled supply change — mid-burn it read TRUE on a 20%-short book.
    function backingInvariantHolds() external view returns (bool);

    /// @notice AUDIT FIX (R16-M4/M5). `max(0, totalUSDfr() - backingValue())` on the RECORDED
    ///         basis — the quantity every supply-affecting path refuses to increase.
    /// @dev AUDIT FIX (R18): reverts with `Controller_ViewUnavailableMidTransition` if called from
    ///      inside an unsettled supply change; it composes a supply reading with a backing reading.
    function backingDeficit() external view returns (uint256);

    /// @notice AUDIT FIX (R16-M4). The same quantity on the RECOGNITION-AWARE basis (net of any
    ///         observable custody shortfall).
    /// @dev This is what `WaterfallEngine.distribute` gates on, comparing it before and after the
    ///      call. Non-worsening rather than absolute, so a repayment that REPAIRS backing is not
    ///      refused merely because the protocol was already short — which is what previously
    ///      turned a single conservative mark into a total halt of repayment processing.
    /// @dev AUDIT FIX (R18): reverts with `Controller_ViewUnavailableMidTransition` if called from
    ///      inside an unsettled supply change, as `backingDeficit()` does.
    function recognizedDeficit() external view returns (uint256);

    /// @notice AUDIT FIX (R16-M5, corrected by R17, R18 and SWEEP-2 S2-F4). How much NEW supply may
    ///         be minted without widening the deficit or paying away value the protocol owes:
    ///         `(paused() || USDfr.paused()) ? 0 : max(0, recognizedBackingValue() - totalUSDfr() -
    ///         seniorSubParShortfall() - ReserveManager.exitPrepaidAbsorption())`.
    /// @dev AUDIT FIX (SWEEP-2 S2-F4) — THE FOURTH TERM WAS MISSING FROM THIS PUBLISHED FORMULA, AND
    ///      THE STRING `exitPrepaid` APPEARED NOWHERE IN THIS FILE. ADR-0034 Y-bis added
    ///      `ReserveManager.exitPrepaidAbsorption()` to the implementation and not to the
    ///      specification. This is the one view that decides how much yield may be minted, and
    ///      `mintYield`'s note below warns that "a caller that does not size itself off
    ///      `mintableHeadroom()` will revert rather than withhold" — so a caller sizing off the
    ///      PUBLISHED formula got `Controller_SeniorRetentionBreached` /
    ///      `Controller_RecognizedDeficitWorsened` instead of a withholding. MEASURED: published
    ///      formula 9,900.99e18, code 0, undocumented term 9,900.99e18. The retention has NO
    ///      RESTITUTION PATH and is not necessarily released — see `mintableHeadroom`'s own
    ///      implementation note and the SWEEP-2 S2-F3 register entry.
    /// @dev AUDIT FIX (R18): the pause term reads BOTH pauses. R17 read only the controller's, while
    ///      the same guardian key holds `GUARDIAN_ROLE` on `USDfr` and a token pause refuses every
    ///      mint — so one transaction still reverted every interest-bearing
    ///      `WaterfallEngine.distribute` in full. `WaterfallEngine.fund` now sizes its origination
    ///      fee off this view as well, so under either pause it withholds the fee instead of
    ///      reverting the origination.
    /// @dev AUDIT FIX (R18): reverts with `Controller_ViewUnavailableMidTransition` if called from
    ///      inside an unsettled supply change — mid-cascade it read the entire realised loss as
    ///      distributable yield capacity.
    /// @dev `WaterfallEngine._routeInterest` reads this and distributes only what fits,
    ///      WITHHOLDING the rest so the cash stays in the reserve and repairs backing. That is
    ///      the protocol-native cure for a residual deficit: loan interest closes the hole
    ///      automatically, with no governance action and no recapitalisation, and yield resumes
    ///      by itself once it is closed.
    /// @dev AUDIT FIX (R17): the basis is RECOGNITION-AWARE. Measured on the recorded ledger the
    ///      cure was blind to the entire deficit class R4-01 exists to recognise — a custody hole
    ///      left headroom equal to the whole interest receipt, so the clamp withheld nothing, the
    ///      protocol fee was taken on the gross, and the hole never closed while every user was
    ///      frozen out of `mint` and `redeem`. It is also zero while the controller is PAUSED, so
    ///      the pause withholds yield instead of reverting every borrower repayment, and it nets
    ///      out `seniorSubParShortfall()`.
    function mintableHeadroom() external view returns (uint256);

    /// @notice AUDIT FIX (R17). Cumulative value crystallised out of the senior layer by sub-par
    ///         exits, in 18-decimal USD. Monotonically non-decreasing; no setter.
    /// @dev Sub-par exits are priced against `recognizePrincipalImpairment` marks, which are
    ///      REVERSIBLE by design (`releasePrincipalImpairment`). The exiter's loss is not. Without
    ///      this, value recovered when a mark is released reappeared as `mintableHeadroom()` and
    ///      was minted to the `sUSDfr` vault — the senior's haircut becoming the yield layer's
    ///      income, ahead of the §1.3 cascade's first two layers. Netting it out of the headroom
    ///      keeps recovered value in the pool as coverage instead. Reconstructable from
    ///      `SeniorShortfallCrystallised` events.
    /// @dev AUDIT FIX (R18) — WHAT IT COSTS, CORRECTED. `mintYield` enforces this as an ABSOLUTE
    ///      level check, so it withholds ORIGINATION FEES as well as interest, and it does so in
    ///      states the protocol publishes as fully backed and even OVER-backed. Under R17 that
    ///      REFUSED `WaterfallEngine.fund` outright and therefore blocked the only cure the
    ///      mechanism names (interest requires a facility; a facility requires `fund`) — finding M5
    ///      on the origination axis. `fund` now clamps its fee to `mintableHeadroom()` and withholds
    ///      instead. The retention is unchanged. Read `MintRedeemController.seniorSubParShortfall`
    ///      for the full statement, including the known over-charge on a REALISED (as opposed to
    ///      released) loss, which is outstanding.
    function seniorSubParShortfall() external view returns (uint256);

    /// @notice AUDIT FIX (R16-M3/L3). Quotes a redemption without executing it: the USDC that
    ///         would be paid and the USDfr that would actually be burned.
    /// @dev Returns `(0, 0)` — BOTH components — in FOUR cases: the amount is below the settleable
    ///      floor; the protocol has no backing; the protocol is empty (`totalUSDfr() == 0`); or
    ///      REDEMPTION IS CLOSED because the reserve has an unreconciled custody shortfall
    ///      (`idleCustodyShortfall() != 0`, AUDIT FIX R18). In all four, nothing is payable at any
    ///      size, which is what `(0, 0)` has always meant here. A frontend can therefore state the
    ///      floor, or state that redemption is unavailable, without simulating a revert.
    /// @dev AUDIT FIX (R18) added the fourth case. R17 changed WHICH number this published over a
    ///      custody hole; it did not change WHETHER one was published, so in the standing R4-01
    ///      state — where `backingInvariantHolds()` already publishes FALSE — this returned a full,
    ///      settleable-looking quote for a call that `_requireCustodiedReserve` then refuses with
    ///      `Controller_ReserveCustodyShortfall`. Passing that number back in as `minUsdcOut`, as
    ///      the sentence above directs, reverted.
    /// @dev AUDIT FIX (R18): reverts with `Controller_ViewUnavailableMidTransition` if called from
    ///      inside an unsettled supply change (the participation-points hook fires mid-burn, where
    ///      this view quoted PAR on a short book).
    /// @dev AUDIT FIX (R17), correcting R16's claim that "quote and settlement cannot diverge".
    ///      This view shares `redeem`'s ARITHMETIC; it does not share `redeem`'s preconditions and
    ///      it does not bind the price. Two consequences a caller must know:
    ///        - It is priced on `recognizedBackingValue()`, because unlike `redeem` it is not
    ///          behind `_requireCustodiedReserve`. On the recorded basis it published a par quote
    ///          in exactly the state where the recorded ledger is known to be false and the call it
    ///          quoted for would revert. Wherever `redeem` is reachable the two bases are equal, so
    ///          the quote is exact there.
    ///        - It is a snapshot of the current state, valid for that state only. Pass it back into
    ///          `redeem(usdfrAmount, minUsdcOut)`; that parameter, not this view, is what binds.
    function previewRedeem(uint256 usdfrAmount) external view returns (uint256 usdcOut, uint256 usdfrIn);

    /// @notice AUDIT FIX (R16-M1). True if `account` may receive `mintYield`.
    function isYieldSink(address account) external view returns (bool);

    /// @notice AUDIT FIX (R16-M1/M2). True if `account` may be burned from by `burnLoss`.
    function isLossSource(address account) external view returns (bool);

    /// @notice Wired module addresses, used to bind ReserveManager's independent loss check to
    ///         the controller that actually points back to that reserve.
    function modules() external view returns (address usdfr, address compliance, address reserves);
}

src/interfaces/IReserveManager.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;

/// @title IReserveManager
/// @notice Mainnet-v1 treasury for canonical USDC and deployed facility principal.
/// @dev USD values use 18 decimals. USDC amounts use the token's native 6 decimals.
interface IReserveManager {
    /// @notice One-time settlement-liquidity initialization has already completed.
    error ReserveManager_SettlementLiquidityAlreadyInitialized();
    /// @notice An opening allowance cannot exceed the canonical recorded idle reserve.
    error ReserveManager_InvalidSettlementOpening(uint256 opening, uint256 idle);
    /// @notice Legacy opening allowance was independently reconciled to retained servicing cash.

    event SettlementLiquidityInitialized(uint256 openingAssets, bytes32 indexed evidenceHash);
    /// @notice A primary inflow begins its exact existing-cooldown qualification period.
    event SettlementPrimaryRecorded(uint64 indexed at, uint256 assets);
    /// @notice An outflow cancels newest unseasoned primary amounts without resetting older ages.
    event SettlementPrimaryCanceled(uint256 assets);
    /// @notice Reconstructable settlement-eligibility transition after a measured cash movement.
    event SettlementLiquidityAdjusted(uint256 previous, uint256 current);
    /// @notice Cash that may enlarge settlement budgets after primary inflows season through the existing cooldown.

    function settlementLiquidity() external view returns (uint256);
    /// @notice One-time legacy allowance; refuses once the preliminary monitor is enabled.
    function initializeSettlementLiquidity(uint256 openingAssets, bytes32 evidenceHash) external;

    /// @notice Pinned history terms for the monitored, execution-time-clamped legacy opening.
    /// @dev Every value comes from the hash-bound history record and equals the release guard's immutables.
    struct MonitoredOpening {
        bytes32 monitorEvidence; // Permanent preliminary-monitor genesis commitment.
        uint256 pinnedCashOutflows; // Monitor cashOutflows observed at the history pin.
        uint256 pinnedProtectedRounding; // Monitor protectedRounding observed at the history pin.
        uint256 qualified; // Conservative qualified-cash lower bound at the history pin.
        uint256 selected; // Reviewed upper cap on the opening (at most `qualified`).
        uint256 buffer; // Physical idle retained outside the opening.
        uint256 roundingCreditCap; // Largest post-pin protected rounding credited; zero requires none.
    }

    /// @notice The legacy monitor at execution is absent, reset or not the one the history pinned.
    error ReserveManager_MonitorMismatch();
    /// @notice A monitor counter is below its pinned observation.
    error ReserveManager_MonitorRegressed(uint256 pinned, uint256 current);
    /// @notice Post-pin protected rounding exceeds the reviewed credit cap.
    error ReserveManager_RoundingCreditExceeded(uint256 credit, uint256 cap);
    /// @notice A monitored opening may credit at most 1e15 of protected rounding.
    error ReserveManager_InvalidRoundingCreditCap(uint256 cap);
    /// @notice The monitored opening must retain exactly the reviewed 50,000-USDfr buffer.
    error ReserveManager_InvalidOpeningBuffer(uint256 buffer);
    /// @notice A selected opening cannot exceed its independently qualified history.
    error ReserveManager_InvalidMonitoredSelection(uint256 selected, uint256 qualified);
    /// @notice An enabled preliminary monitor requires the clamped initialization path.
    error ReserveManager_MonitoredOpeningRequired();
    /// @notice The execution-time opening: min(selected, qualified - spent, idle - buffer).

    event SettlementOpeningClamped(
        uint256 selected, uint256 qualified, uint256 spentSincePin, uint256 bufferedIdle, uint256 opening
    );
    /// @notice Junior capital consumed by native rounding between the history pin and execution.
    event PreReleaseRoundingCredited(uint256 pinned, uint256 current, uint256 credit);

    /// @notice One-time governed legacy opening clamped at execution from the preliminary monitor.
    /// @dev Opens min(selected, qualified - (cashOutflows - pinned), idle - buffer); never reverts on
    ///      outflows. Records post-pin protected rounding into this reserve's loss-protection record.
    function initializeMonitoredSettlementLiquidity(MonitoredOpening calldata terms, bytes32 evidenceHash) external;
    /// @notice Current qualified amount and initialization state for migration and monitoring.
    function settlementLiquidityStatus() external view returns (bool initialized, uint256 eligible);

    /// @notice Recognition or an opening import makes a return to legacy accounting unsafe.
    error ReserveManager_LegacyRollbackUnsafe();

    /// @notice Refuses a legacy-code rollback once accrual activation or migration has started.
    /// @dev Read-only execution guard for a governance batch, not authority to upgrade.
    function requireLegacyRollbackSafe() external view;

    /// @notice Canonical USDC was pulled into recorded idle custody.
    event USDCDeposited(address indexed from, uint256 requested, uint256 credited);
    /// @notice Canonical USDC was released from recorded idle custody.
    event USDCReleased(address indexed to, uint256 amount);
    /// @notice A permissionless observation compared recorded and live USDC custody.
    event IdleUSDCObserved(uint256 recorded, uint256 live, uint256 shortfall);
    /// @notice An adjudicated custody loss reduced recorded idle backing.
    event IdleUSDCWrittenDown(uint256 amount, uint256 remaining);
    /// @notice Returned USDC was credited against one arm's written-down recovery capacity.
    event RecoveredIdleUSDCCredited(
        uint256 indexed armId, uint256 nativeUnits, uint256 value, bytes32 indexed evidenceHash
    );
    /// @notice A custody loss reduced backing and fixed the supply reduction the cascade must absorb.
    event ReserveLossRecognized(
        uint256 indexed incidentId, uint256 backingReduction, uint256 surplusAbsorbed, uint256 supplyReductionRequired
    );
    /// @notice The complete surplus-to-senior allocation of one recognized custody loss.
    event ReserveLossAllocated(
        uint256 indexed incidentId,
        uint256 backingReduction,
        uint256 surplusAbsorbed,
        uint256 curatorAbsorbed,
        uint256 backstopCovered,
        uint256 seniorBurned,
        uint256 residualDeficit
    );
    /// @notice The controller used for supply, backing, and loss-burn checks changed.
    event LossControllerSet(address indexed previousController, address indexed newController);
    /// @notice The ordered custody-cascade and governance timing modules were wired.
    event ReserveLossModulesSet(
        address indexed curator, address indexed backstop, address indexed vault, address governor, address timelock
    );
    /// @notice A Guardian created a persistent reserve-loss interlock and evidence commitment.
    event ReserveLossArmed(uint256 indexed armId, uint256 indexed incidentId, bytes32 evidenceHash);
    /// @notice Governance cancelled an unused arm and disabled future Guardian arms.
    event ReserveLossArmCancelled(uint256 indexed armId, bytes32 indexed evidenceHash);
    /// @notice Governance cancelled a custody false alarm while retaining all credit marks.
    event UnratifiedReserveLossArmCancelled(
        uint256 indexed armId, bytes32 indexed evidenceHash, uint256 retainedPrincipalImpairment
    );
    /// @notice A previously ratified arm must use the incident settlement path.

    error ReserveManager_ArmAlreadyRatified(uint256 armId);

    /// @notice Governance closed the arm-bound incident and disabled future Guardian arms.
    event ReserveLossArmFinalized(uint256 indexed armId, uint256 indexed incidentId, bytes32 indexed evidenceHash);
    /// @notice Governance ratified and executed the current objective custody shortfall.
    event ReserveLossRatified(
        uint256 indexed armId,
        uint256 indexed incidentId,
        uint256 approvedMaxLoss,
        uint256 actualLoss,
        bytes32 evidenceHash
    );
    /// @notice Governance enabled or disabled creation of new Guardian reserve-loss arms.
    event GuardianReserveLossArmsEnabled(bool enabled);
    /// @notice A custody-loss incident entered the active register under its bound arm.
    event ReserveLossIncidentOpened(uint256 indexed incidentId, uint256 indexed armId, bytes32 evidenceHash);
    /// @notice The active custody-loss incident left the register.
    event ReserveLossIncidentClosed(uint256 indexed incidentId);
    /// @notice A cascade changed the latched unabsorbed reserve deficit.
    event ReserveDeficitUpdated(uint256 indexed incidentId, uint256 previousDeficit, uint256 currentDeficit);
    /// @notice Governance cleared a cured reserve-deficit latch with supporting evidence.
    event ReserveDeficitResolved(uint256 previousDeficit, bytes32 evidenceHash);
    /// @notice Idle USDC became deployed principal for a facility.
    event PrincipalDeployed(uint256 indexed facilityId, uint256 amount);
    /// @notice A retained origination fee became additional facility principal.
    event FeeCapitalized(uint256 indexed facilityId, uint256 amount);

    /// @notice Contractually accrued PIK interest joined a facility's deployed principal.
    /// @dev No cash moved and, unlike `FeeCapitalized`, none was retained either.
    /// @param facilityId The facility.
    /// @param amount 18-decimal value capitalised.
    /// @param deployedAfter The facility's deployed principal after the act.
    event PikCapitalized(uint256 indexed facilityId, uint256 amount, uint256 deployedAfter);
    /// @notice A cash receipt increased idle custody and reduced the stated principal leg.
    event PaymentReceived(
        uint256 indexed facilityId, address indexed payer, uint256 usdcAmount, uint256 principalReturned
    );
    /// @notice Realized facility principal was removed from backing.
    event PrincipalWrittenDown(uint256 indexed facilityId, uint256 amount);
    /// @notice Governance added an evidence-backed conservative facility impairment.
    event PrincipalImpairmentRecognized(
        uint256 indexed facilityId,
        uint256 amount,
        uint256 facilityImpairment,
        uint256 totalImpairment,
        uint256 backingAfter,
        bytes32 evidenceHash
    );
    /// @notice Governance released part of an evidence-backed conservative facility impairment.
    event PrincipalImpairmentReleased(
        uint256 indexed facilityId,
        uint256 amount,
        uint256 facilityImpairment,
        uint256 totalImpairment,
        bytes32 evidenceHash
    );
    /// @notice A principal write-down consumed the corresponding previously recognized impairment.
    event PrincipalImpairmentRealized(
        uint256 indexed facilityId, uint256 amount, uint256 facilityImpairment, uint256 totalImpairment
    );
    /// @notice The retained compatibility loss-absorber binding changed.
    event LossAbsorberSet(address indexed previousAbsorber, address indexed newAbsorber);
    /// @notice A funder supplied new canonical USDC backing without minting claims.
    event Recapitalized(
        address indexed funder, uint256 units, uint256 credited, uint256 backingAfter, uint256 deficitOutstanding
    );
    /// @notice A senior-exit junior draw was added to the historical prepayment ledger.
    event ExitPrepaymentRecorded(uint256 amount, uint256 outstanding);
    /// @notice A facility loss consumed part of the historical exit-prepayment ledger.
    event ExitPrepaymentConsumed(uint256 indexed facilityId, uint256 consumed, uint256 outstanding);
    /// @notice A custody loss consumed the surplus backing part of an exit prepayment.
    event ExitPrepaymentAbsorbedByCustody(uint256 indexed incidentId, uint256 consumed, uint256 outstanding);
    /// @notice Governance permanently bound the borrower-payout policy used before USDC deployment.
    event BorrowerPayoutRegistrySet(address indexed registry);

    /// @notice Requested USDC value exceeds recorded idle value.
    error ReserveManager_InsufficientIdleValue(uint256 requestedValue, uint256 idleValue);
    /// @notice Requested principal reduction exceeds the facility's live deployed principal.
    error ReserveManager_InsufficientDeployedPrincipal(uint256 facilityId, uint256 requested, uint256 deployed);
    /// @notice A value-moving call supplied a zero amount.
    error ReserveManager_ZeroAmount();
    /// @notice A required account or module address is zero.
    error ReserveManager_ZeroAddress();
    /// @notice The caller is not an authorised controller or credit depositor.
    error ReserveManager_NotDepositor(address caller);
    /// @notice A pull expected canonical USDC but received no value.
    error ReserveManager_NoValueReceived();
    /// @notice The token balance delta differed from the requested USDC transfer.
    error ReserveManager_UnexpectedUSDCReceipt(uint256 expected, uint256 received);
    /// @notice A legacy idle write-down exceeds recorded idle value.
    error ReserveManager_WriteDownExceedsIdle(uint256 amount, uint256 idle);
    /// @notice A USDC release or deployment attempted to target the ReserveManager itself.
    error ReserveManager_SelfDeployment();
    /// @notice An 18-decimal value cannot be represented exactly in native USDC units.
    error ReserveManager_ValueNotUSDCExact(uint256 value);
    /// @notice The configured custody token does not use canonical USDC's six decimals.
    error ReserveManager_InvalidUSDCDecimals(uint8 decimals);
    /// @notice A payment allocated more principal than the USDC value actually received.
    error ReserveManager_PrincipalExceedsPayment(uint256 principal, uint256 paymentValue);
    /// @notice A proposed curator, backstop, vault, or absorber fails its binding contract.
    error ReserveManager_InvalidLossAbsorber(address absorber);
    /// @notice A proposed controller fails its module and reserve binding contract.
    error ReserveManager_InvalidLossController(address controller);
    /// @notice A loss layer's reported burn differs from the observed USDfr supply reduction.
    error ReserveManager_LossAbsorberContractViolated(uint256 backingReduction, uint256 supplyBurned);
    /// @notice Reported cascade allocation does not reconcile to the recognized loss.
    error ReserveManager_LossAllocationMismatch(
        uint256 expectedSurplus, uint256 reportedSurplus, uint256 expectedAccounted, uint256 reportedAccounted
    );
    /// @notice The terminal live supply/backing deficit differs from the cascade calculation.
    error ReserveManager_PostLossDeficitMismatch(uint256 expectedDeficit, uint256 observedDeficit);
    /// @notice A custody incident id has already been consumed.
    error ReserveManager_IncidentAlreadyUsed(uint256 incidentId);
    /// @notice A new arm or incident cannot replace the currently active incident.
    error ReserveManager_IncidentAlreadyActive(uint256 incidentId);
    /// @notice A terminal action requires an active custody incident.
    error ReserveManager_NoActiveIncident();
    /// @notice The supplied custody incident does not match the active incident.
    error ReserveManager_IncidentMismatch(uint256 expected, uint256 supplied);
    /// @notice The caller lacks the reserve-administration authority required for the live loss path.
    error ReserveManager_ReserveLossCallerNotAdmin(address caller);
    /// @notice A reserve-loss allocation used an id outside the custody-event namespace.
    error ReserveManager_InvalidReserveLossIncident(uint256 incidentId);
    /// @notice A cascade was requested without a recognized supply reduction.
    error ReserveManager_NoRecognizedReserveLoss();
    /// @notice Finalization was attempted while recognized loss remains unallocated.
    error ReserveManager_RecognizedLossOutstanding(uint256 amount);
    /// @notice Finalization was attempted while live USDC custody remains short.
    error ReserveManager_LiveShortfallExists(uint256 nativeUnits);
    /// @notice Finalization was attempted while supply still exceeds backing.
    error ReserveManager_DeficitStillExists(uint256 recordedDeficit, uint256 observedDeficit);
    /// @notice Creation of new Guardian reserve-loss arms is disabled.
    error ReserveManager_GuardianArmsDisabled();
    /// @notice A new arm cannot replace the currently active arm.
    error ReserveManager_ArmAlreadyActive(uint256 armId);
    /// @notice An arm-bound action requires an active arm.
    error ReserveManager_NoActiveArm();
    /// @notice The supplied arm id does not match the active arm.
    error ReserveManager_ArmMismatch(uint256 expected, uint256 supplied);
    /// @notice Ratification evidence does not match the Guardian's armed commitment.
    error ReserveManager_ArmEvidenceMismatch(bytes32 expected, bytes32 supplied);
    /// @notice The monotonic arm id space is exhausted.
    error ReserveManager_ArmIdExhausted();
    /// @notice Ratification found that the objective custody shortfall was already cured.
    error ReserveManager_ShortfallCured();
    /// @notice The live custody loss exceeds governance's approved maximum.
    error ReserveManager_LossExceedsApproval(uint256 actualLoss, uint256 approvedMaxLoss);
    /// @notice No physically returned USDC is available for the supplied arm.
    error ReserveManager_NoRecoveredUSDC(uint256 armId);
    /// @notice Finalization found returned USDC that has not yet been credited.
    error ReserveManager_RecoveredUSDCNotCredited(uint256 armId, uint256 nativeUnits);
    /// @notice The superseded arbitrary idle-write-down entry is permanently disabled.
    error ReserveManager_LegacyPathDisabled();
    /// @notice Cancellation would release an interlock while a loss condition remains live.
    error ReserveManager_InterlockReleaseForbidden();
    /// @notice Loss-module rebinding is forbidden while an arm, incident, shortfall, or deficit is live.
    error ReserveManager_ModuleRebindForbidden();
    /// @notice The proposed governor and timelock do not expose one coherent live timing path.
    error ReserveManager_InvalidGovernanceTiming(address governor, address timelock);
    /// @notice An evidence-backed transition supplied the zero evidence hash.
    error ReserveManager_ZeroEvidenceHash();
    /// @notice A conservative impairment would exceed the facility's remaining face principal.
    error ReserveManager_ImpairmentExceedsFace(uint256 facilityId, uint256 requested, uint256 remainingFace);
    /// @notice An impairment release exceeds the amount currently recognized for the facility.
    error ReserveManager_ImpairmentReleaseExceedsRecognized(uint256 facilityId, uint256 requested, uint256 recognized);
    /// @notice The caller is not the retained compatibility loss absorber.
    error ReserveManager_NotLossAbsorber(address caller);
    /// @notice Recorded idle USDC exceeds live custody, so a protected out-door is closed.
    error ReserveManager_IdleCustodyShortfall(uint256 recordedUnits, uint256 liveUnits);
    /// @notice A legacy incident nonce is zero or enters the reserved custody namespace.
    error ReserveManager_InvalidIncidentNonce(uint256 incidentNonce);
    /// @notice Deficit resolution was requested without a recorded deficit.
    error ReserveManager_NoReserveDeficit();
    /// @notice An incident close requires its recorded deficit to be resolved first.
    error ReserveManager_DeficitResolutionRequired(uint256 recordedDeficit);
    /// @notice The borrower-payout policy was already bound and cannot be replaced.
    error BorrowerPayout_RegistryAlreadySet(address registry);
    /// @notice A proposed borrower-payout policy has no compatible code.
    error BorrowerPayout_InvalidRegistry(address registry);
    /// @notice Loan proceeds may not be directed to this address.
    error BorrowerPayout_RecipientNotAllowed(address recipient);

    /// @notice Pulls exact canonical USDC from `from` into recorded idle custody.
    function depositUSDC(address from, uint256 amount) external returns (uint256 credited);
    /// @notice Releases recorded idle USDC through the controller-only redemption path.
    function releaseUSDC(address to, uint256 amount) external;

    /// @notice Permanently binds the timelock-managed borrower-payout registry.
    function setBorrowerPayoutRegistry(address registry) external;

    /// @notice The permanent borrower-payout policy, or zero before the required binding.
    function borrowerPayoutRegistry() external view returns (address);

    /// @notice Permissionlessly checkpoints the objective live-vs-recorded custody shortfall.
    /// @dev Observation never changes backing and never moves junior or senior capital.
    /// @return shortfall Native six-decimal USDC units missing from custody.
    function reconcileIdleUSDC() external returns (uint256 shortfall);

    /// @notice Permissionless live-vs-recorded custody observation; never changes accounting.
    function observeIdleUSDC() external view returns (uint256 recorded, uint256 live, uint256 shortfall);

    /// @notice Native USDC units by which recorded idle custody exceeds the live token balance.
    function idleCustodyShortfall() external view returns (uint256);
    /// @notice Recorded backing net of any physically observable idle-custody shortfall.
    function recognizedBackingValue() external view returns (uint256);
    /// @notice Whether an arm, incident, recognized loss, deficit, or live shortfall locks exits.
    function custodyLossUnabsorbed() external view returns (bool);

    /// @notice Wires the controller used for direct supply/backing and loss-burn checks.
    function setLossController(address controller) external;
    /// @notice Wires the retained compatibility absorber after verifying its reserve binding.
    function setLossAbsorber(address absorber) external;

    /// @notice Legacy incident controls retained as non-credit compatibility surfaces while
    ///         new custody accounting uses the arm-bound ratification path.
    function openReserveLossIncident(uint256 incidentNonce, bytes32 evidenceHash)
        external
        returns (uint256 incidentId);
    /// @notice Closes the exact active legacy incident once no deficit remains.
    function closeReserveLossIncident(uint256 incidentId) external;
    /// @notice Clears a cured legacy reserve-deficit latch with supporting evidence.
    function resolveReserveDeficit(bytes32 evidenceHash) external;
    /// @notice Canonical USDC held above the amount recorded as idle custody.
    function unrecordedUSDC() external view returns (uint256);

    /// @notice Wires the ordered custody cascade and its live governance timing sources.
    function setReserveLossModules(address curator, address backstop, address vault, address governor, address timelock)
        external;

    /// @notice Guardian-only persistent interlock created before an amount-bearing proposal.
    /// @return armId Monotonic internal id consumed only by an explicit governance terminal action.
    /// @return incidentId Structurally bound upper-half custody event id.
    function armReserveLossFreeze(bytes32 evidenceHash) external returns (uint256 armId, uint256 incidentId);

    /// @notice Governance consumes an unused arm only when the objective shortfall is zero and
    ///         no adjudicated loss, incident or deficit exists; future Guardian arms stay disabled.
    function cancelAndDisable(uint256 expectedArmId, bytes32 evidenceHash) external;

    /// @notice Cancels an unratified custody false alarm and disables further guardian arms.
    /// @dev Requires accounted custody and no unsettled custody incident or reserve deficit.
    ///      Independent credit impairment and exit prepayments remain unchanged.
    /// @param expectedArmId Exact active arm being cancelled.
    /// @param evidenceHash Nonzero commitment to the governance resolution evidence.
    function cancelUnratifiedArm(uint256 expectedArmId, bytes32 evidenceHash) external;

    /// @notice Governance kill switch for repeated Guardian arms.
    function setGuardianReserveLossArmsEnabled(bool enabled) external;

    /// @notice Governance ratifies and atomically absorbs the live objective shortfall, bounded
    ///         by the amount approved in the proposal. Every tranche under an arm reuses its id
    ///         and must supply the Guardian's exact armed evidence commitment.
    function ratifyAndOpen(uint256 expectedArmId, bytes32 evidenceHash, uint256 approvedMaxLoss)
        external
        returns (uint256 incidentId, uint256 actualLoss);

    /// @notice Credits physically returned canonical USDC without minting USDfr, capped by the
    ///         amount previously written down under `armId`. May execute after incident closure.
    function creditRecoveredIdleUSDC(uint256 armId, bytes32 evidenceHash) external returns (uint256 credited);

    /// @notice Atomically resolves a cured deficit, closes the arm-bound incident and disables
    ///         future Guardian arms. It cannot release a shortfall or uncredited returned USDC.
    function finalizeAndDisable(uint256 expectedArmId, bytes32 evidenceHash) external;

    /// @notice Pulls new canonical USDC backing without minting USDfr claims.
    function recapitalize(uint256 amount) external returns (uint256 credited);

    /// @notice Controller used for supply, backing, and loss-burn verification.
    function lossController() external view returns (address);
    /// @notice Ordered curator, backstop, vault, governor, and timelock bindings.
    function reserveLossModules()
        external
        view
        returns (address curator, address backstop, address vault, address governor, address timelock);
    /// @notice Active custody incident id and its evidence commitment.
    function activeReserveLossIncident() external view returns (uint256 incidentId, bytes32 evidenceHash);
    /// @notice Whether a custody incident id has already entered the durable register.
    function reserveLossIncidentUsed(uint256 incidentId) external view returns (bool);
    /// @notice Latched portion of adjudicated custody losses not absorbed by any capital layer.
    function reserveDeficit() external view returns (uint256);
    /// @notice Current recognized backing reduction and pending cascade requirement.
    function recognizedReserveLoss()
        external
        view
        returns (uint256 backingReduction, uint256 surplusAbsorbed, uint256 supplyReductionRequired);
    /// @notice Active arm identity, derived incident, armed evidence, and future-arm switch.
    function reserveLossArm()
        external
        view
        returns (uint256 armId, uint256 incidentId, bytes32 evidenceHash, bool armsEnabled);
    /// @notice Native USDC recovery capacity created by write-downs under one arm.
    function reserveLossRecoveryCapacity(uint256 armId) external view returns (uint256 nativeUnits);
    /// @notice Retained compatibility absorber bound to this reserve.
    function lossAbsorber() external view returns (address);
    /// @notice Historical junior prepayment still available for impairment release.
    function exitPrepaidAbsorption() external view returns (uint256);
    /// @notice Records a senior-exit junior draw in the compatibility prepayment ledger.
    function recordExitPrepayment(uint256 amount) external;
    /// @notice Consumes prepayment only against recognized impairment for a facility loss.
    function consumeExitPrepayment(uint256 facilityId, uint256 loss) external returns (uint256 used);

    /// @notice Shared fail-closed interlock consumed by curator withdrawals and queue settlement.
    function reserveLossExitsLocked() external view returns (bool);

    /// @notice Backwards-compatible semantic alias used by CuratorModule.
    function curatorWithdrawalsLocked() external view returns (bool);

    /// @notice Converts exact recorded idle USDC into deployed facility principal.
    function recordDeployment(uint256 facilityId, address to, uint256 usdcAmount) external;
    /// @notice Adds retained origination-fee cash as facility principal without moving custody.
    function recordFeeCapitalization(uint256 facilityId, uint256 amount) external;

    /// @notice Capitalises accrued PIK interest into a facility's deployed principal. No cash moves.
    /// @dev CREDIT_ROLE, and in practice `WaterfallEngine.capitalizePik` alone, which carries every
    ///      bound. See `ReserveManager.recordPikCapitalization` for why there is no idle check.
    /// @param facilityId The facility.
    /// @param amount 18-decimal value to capitalise, exact on the USDC grid.
    function recordPikCapitalization(uint256 facilityId, uint256 amount) external;

    /// @notice Atomically pulls exact USDC and accounts the principal leg.
    function recordPayment(uint256 facilityId, address payer, uint256 usdcAmount, uint256 principal)
        external
        returns (uint256 receivedValue);

    /// @notice Removes realized facility principal and consumes its corresponding impairment.
    function recordPrincipalWritedown(uint256 facilityId, uint256 amount) external;

    /// @notice Records an evidence-backed conservative mark without moving face principal or
    ///         allocating the loss between capital layers.
    function recognizePrincipalImpairment(uint256 facilityId, uint256 amount, bytes32 evidenceHash) external;

    /// @notice Reverses a conservative mark, bounded by the amount previously recognized.
    function releasePrincipalImpairment(uint256 facilityId, uint256 amount, bytes32 evidenceHash) external;

    /// @notice Recorded idle custody expressed as 18-decimal USDfr value.
    function idleReserve() external view returns (uint256);
    /// @notice Recorded idle custody in native six-decimal USDC units.
    function idleUSDC() external view returns (uint256);
    /// @notice Aggregate deployed facility principal before conservative impairments.
    function deployedPrincipal() external view returns (uint256);
    /// @notice Aggregate evidence-backed conservative principal impairment.
    function totalPrincipalImpairment() external view returns (uint256);
    /// @notice Evidence-backed conservative impairment recorded for one facility.
    function principalImpairmentOf(uint256 facilityId) external view returns (uint256);
    /// @notice Recorded idle plus deployed principal, net of conservative impairments.
    function totalBackingValue() external view returns (uint256);
    /// @notice Outstanding receivable face deployed to one facility.
    /// @dev Continuous accrual includes earned but unreceived cash and PIK interest.
    function deployedTo(uint256 facilityId) external view returns (uint256);
    /// @notice Canonical six-decimal USDC token held by the reserve.
    function usdc() external view returns (address);
    /// @notice Converts native six-decimal USDC units to 18-decimal protocol value.
    function normalizeUSDC(uint256 amount) external pure returns (uint256);
    /// @notice Converts exact 18-decimal protocol value to native USDC units.
    function denormalizeUSDC(uint256 value) external pure returns (uint256);
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 100,
    "enabled": true
  },
  "evmVersion": "cancun",
  "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/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.