Skip to content
Verified contractPartialUNLICENSED

WarehouseTreasury

Address0xe573bbd3fba6886b3ac328aee4cfddd4623ca1f0
Balance

0 ETH

 

Transactions

106

 

Compiler

solc 0.8.27

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.27+commit.40a35a09
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
UNLICENSED
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,357,810
Creation transaction
0x979fe117ce…e4699111d4
Libraries
src/libraries/TreasuryCow.sol:TreasuryCow0xfdfd…4b8c0fsrc/libraries/TreasuryFold.sol:TreasuryFold0x167e…453043src/libraries/TreasurySales.sol:TreasurySales0x1780…949d2a

50 files

src/WarehouseTreasury.sol

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

import {ISalePricingEvents} from "./libraries/SalePricing.sol";

import {Treasury} from "./Treasury.sol";
import {IPRUSD} from "./interfaces/IPRUSD.sol";
import {ISettlementPool7540} from "./interfaces/ISettlementPool7540.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Roles} from "./libraries/Roles.sol";
import {CollateralConfig} from "./types/ProtocolTypes.sol";
import {WarehouseSourceAuth} from "./WarehouseSourceAuth.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IWarehouseCycleSource} from "./interfaces/IWarehouseCycleSource.sol";
import {StableReserveRegistry} from "./registries/StableReserveRegistry.sol";
import {StableReserveVault} from "./StableReserveVault.sol";
import {TreasurySales} from "./libraries/TreasurySales.sol";
import {TreasuryFold} from "./libraries/TreasuryFold.sol";
import {TreasuryCow, ICowLotEvents} from "./libraries/TreasuryCow.sol";
import {Lot, LotHandover} from "./types/LotTypes.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {SupportedChains} from "./libraries/SupportedChains.sol";

interface IRecoveryPool {
    function receiveRecoveryRepayment(uint256 amount) external;
}

/// @dev The reserve's waterfall repair (task 0197).
interface IRepairReserve {
    function repairGap() external view returns (uint256);
    function repairFromTreasury(uint256 amount) external;
}

interface IWarehouseResidualSource {
    function pool() external view returns (address);
    function treasury() external view returns (address);
    function collateralToken() external view returns (address);
    function collateralId() external view returns (uint256);
    function collateralDecimals() external view returns (uint8);
    function residualQuote() external view returns (uint256 cycle, uint256 amount, uint256 stop);
    function liquidationCycleId() external view returns (uint256);
    function liquidationCycleOpen() external view returns (bool);
}

/// @notice Residual buyer; uses canonical inventory and authenticated atomic settlement (mainnet, Sepolia, Anvil).
/// @dev The vault call that frees a facility's borrowing room (0195); the vault admits the facility's own Treasury.
interface IWarehousePrincipalVault {
    function retireWarehouseDebt(uint256 facilityId, uint256 principal, uint256 interest) external;
}

contract WarehouseTreasury is Treasury, ISalePricingEvents, ICowLotEvents {
    using SafeERC20 for IERC20;
    using EnumerableSet for EnumerableSet.UintSet;
    error ResidualMismatch();
    StableReserveRegistry public reserveRegistry;
    event ReserveRegistrySet(address indexed registry);
    event CycleArbitrageExecuted(
        uint256 indexed poolId, uint256 indexed liquidationCycleId, uint256 spent, uint256 minted
    );
    event CycleArbitrageSkipped(
        uint256 indexed poolId, uint256 indexed liquidationCycleId, bytes reason
    );
    /// @notice Cumulative debt taken over from warehouses, per collateral: it only ever rises. It is NOT what is still
    ///         owed; that is each lot's `principal` and `interest` in `lots`. It stays monotonic because the keeper
    ///         uses it to refuse a stale takeover (a changed value means another takeover landed).
    mapping(uint256 collateralId => uint256) public foldedDebt;

    /// @notice One Treasury lot per liquidation handed over by a warehouse takeover (task 0191). Kept out of
    ///         `seizedInventory`, so the SRV recovery path cannot sell it and it never counts as an unwind in flight.

    /// @notice The waterfall lane contract (task 0197), set once. The only caller of the two waterfall entry points.
    address public waterfall;

    mapping(bytes32 lotId => Lot) public lots;
    TreasuryCow.Ledger private _cow;

    function setCowSeller(uint256 cid, address seller) external onlyRole(DEFAULT_ADMIN_ROLE) {
        TreasuryCow.configureSeller(_cow, address(reserveRegistry), seller, cid);
    }

    function cowSellerForCollateral(uint256 cid) external view returns (address) {
        return _cow.sellerForCollateral[cid];
    }

    /// @notice A cycle's collateral still in this contract's custody: what its CoW seller does not hold (0294).
    function recoverableCycleCollateral(uint256 pid, uint256 cycle) public view returns (uint256) {
        return TreasuryCow.recoverableCycleCollateral(_cow, _liquidationCycles, pid, cycle);
    }

    /// @notice Operator custody actions on a configured seller (task 0286): fund a lot or a cycle,
    ///         collect proceeds or return unsold collateral. Every action books completed fills first.
    ///         Sweep a collateral gift, or book unexplained USDC as donation income (0290): booking is a Treasury
    ///         control the linked library authorises to the admin alone, so it skips the hotswap check here. A
    ///         checkpoint here books fills only, as every action but a collection already does before it acts.
    function cowAction(TreasuryCow.Action calldata action) external nonReentrant {
        if (action.kind < TreasuryCow.ActionKind.BookUnclassified) _checkRole(Roles.HOTSWAP_ROLE); // the last kind
        _cowAction(action);
    }

    function _cowAction(TreasuryCow.Action memory action) private {
        _checkOutflow(0); // Reserve issuance must not enter an open revenue checkpoint.
        foldInterestReconciled += TreasuryCow.partialAction(
            _cow, lots, lotCollateral, _folds, _liquidationCycles, action
        );
    }

    /// @dev Only the linked accounting operation, executing inside this Treasury,
    /// can deliver a completion. No keeper-supplied amounts enter this callback.
    function bookCowCompletion(TreasuryCow.Completion calldata c, address asset, address backing)
        external
    {
        if (msg.sender != address(this)) revert ResidualMismatch();
        if (c.source != 0) {
            _book(c.source, c.surplus); // 0290: a gift has no pool, no cycle and no debt
        } else if (c.cycle == 0) {
            foldInterestReconciled += c.interest;
            _resolveExposure(c.poolId, c.collateralId, c.sold, c.surplus);
        } else {
            Recovery memory r;
            r.cid = c.collateralId;
            r.pid = c.poolId;
            r.sold = c.sold;
            r.received = c.received;
            r.minted = c.surplus;
            r.pool = poolRegistry.getPool(c.poolId).pool;
            r.reserve = backing;
            _settleRecovery(r, c.cycle, asset, address(0), "");
        }
    }

    function reservedLotCollateral(bytes32 id) external view returns (uint256) {
        return _cow.reserved[id];
    }

    function externalLotCollateral(uint256 cid) external view returns (uint256) {
        return _cow.externalCollateral[cid];
    }

    /// @notice Cumulative interest-origin folded debt burned or migrated. Reconciles supply, never income.
    uint256 public foldInterestReconciled;
    event FoldLossAllocated(bytes32 indexed lotId, address indexed reserve, uint256 amount);
    event LotLossPending(bytes32 indexed lotId, uint256 principal, uint256 interest);
    event FoldDebtSettled(
        bytes32 indexed lotId, bool migrated, uint256 principal, uint256 interest
    );
    event FoldFacilitySettled(
        bytes32 indexed lotId,
        uint256 indexed facilityId,
        bool migrated,
        uint256 principal,
        uint256 interest
    );
    TreasurySales.CycleLedger private _liquidationCycles;

    function cycleCollateral(uint256 pid, uint256 id) external view returns (uint256) {
        return _liquidationCycles.collateral[pid][id];
    }

    function activeLiquidationCycle(uint256 pid) external view returns (uint256) {
        return _liquidationCycles.active[pid];
    }

    function currentCycleTab(uint256 pid) external view returns (uint256) {
        return _liquidationCycles.tab[pid];
    }

    function heldLiquidationCycleCount(uint256 pid) external view returns (uint256) {
        return _liquidationCycles.held[pid].length();
    }

    function heldLiquidationCycleAt(uint256 pid, uint256 index) external view returns (uint256) {
        return _liquidationCycles.held[pid].at(index);
    }
    event LiquidationCyclePurchase(
        uint256 indexed poolId,
        uint256 indexed liquidationCycleId,
        uint256 indexed biteId,
        uint256 collateral,
        uint256 cash,
        uint256 tab,
        uint256 collateralHeld,
        uint256 tabOutstanding
    );
    event LiquidationCycleRecovery(
        uint256 indexed poolId,
        uint256 indexed liquidationCycleId,
        uint256 sold,
        uint256 minted,
        uint256 tabRepaid,
        uint256 collateralHeld,
        uint256 currentTabOutstanding
    );
    event LiquidationCycleTabClosed(
        uint256 indexed poolId,
        uint256 indexed liquidationCycleId,
        uint256 tabReclassified,
        uint256 collateralHeld
    );
    event LiquidationCycleTabAdjusted(
        uint256 indexed poolId,
        uint256 indexed liquidationCycleId,
        uint256 writtenOff,
        uint256 tabOutstanding
    );

    function cycleCash(uint256 pid, uint256 id) external view returns (uint256) {
        return _liquidationCycles.cash[pid][id];
    }

    function totalCycleCashReserved() external view returns (uint256) {
        return _liquidationCycles.totalCash;
    }

    function reservedRevenue() public view override returns (uint256) {
        return _liquidationCycles.totalRevenue;
    }

    function cycleRevenue(uint256 pid, uint256 id) external view returns (uint256) {
        return _liquidationCycles.revenue[pid][id];
    }

    function spendableCash() public view override returns (uint256) {
        uint256 available = super.spendableCash();
        uint256 reserved = _liquidationCycles.totalCash;
        return available > reserved ? available - reserved : 0;
    }

    function closeLiquidationCycle(uint256 pid, uint256 id) external nonReentrant {
        address pool = poolRegistry.getPool(pid).pool;
        address seller = _cow.sellerForCollateral[ISettlementPool7540(pool).collateralId()];
        // Book every completed fill, including pending rounding remainders, into this cycle before it ends.
        if (seller != address(0)) {
            _cowAction(TreasuryCow.Action(TreasuryCow.ActionKind.Checkpoint, seller, 0, 0, 0));
        }
        TreasurySales.closeCycle(
            _liquidationCycles, address(vault), settlementSource[pool], pool, pid, id
        );
    }

    function settleCycleCash(uint256 pid, uint256 id, uint256 bite) external nonReentrant {
        address pool = poolRegistry.getPool(pid).pool;
        if (settlements[pool][bite].state != SettlementState.Consumed) revert ResidualMismatch();
        (uint256 paid, uint256 revenuePaid) = TreasurySales.settleCycleCash(
            _liquidationCycles,
            address(vault),
            settlementSource[pool],
            pool,
            pid,
            id,
            bite,
            poolLedger[pid].tabOutstanding
        );
        if (paid != 0) {
            attributedOutflows += revenuePaid;
            _repayTab(pid, pool, paid, false);
        }
    }

    function _freeCashRepayableTab(uint256 pid) internal view override returns (uint256) {
        return poolLedger[pid].tabOutstanding - _liquidationCycles.tab[pid];
    }

    function _clampLastSettledCycleTab(uint256 pid, uint256 total) internal override {
        super._clampLastSettledCycleTab(pid, total);
        TreasurySales.clampCycleTab(_liquidationCycles, pid, total);
    }

    function _settlementProfitTab(uint256 pid, uint256 tabCut)
        internal
        override
        returns (uint256 liquidationCycle, uint256 currentTab)
    {
        _liquidationCycles.tab[pid] -= tabCut;
        return (_liquidationCycles.active[pid], _liquidationCycles.tab[pid]);
    }
    TreasurySales.FoldLedger private _folds;

    function lotFacilityDebt(bytes32 id, uint256 fid) external view returns (uint256, uint256) {
        TreasurySales.FacilityBalance storage f = _folds.debt[id][fid];
        return (f.principal, f.interest);
    }

    function lotFacilityCount(bytes32 id) external view returns (uint256) {
        return _folds.facilities[id].length;
    }

    function lotFacilityAt(bytes32 id, uint256 index) external view returns (uint256) {
        return _folds.facilities[id][index];
    }
    /// @notice Collateral the Treasury holds for lots, per collateral id (control total for the lot accounts).
    mapping(uint256 collateralId => uint256) public lotCollateral;

    event LotOpened(
        bytes32 indexed lotId,
        uint256 indexed collateralId,
        uint256 indexed poolId,
        uint256 collateral,
        uint256 principal,
        uint256 interest,
        uint256 facilityId
    );
    event AggregateLotOpened(
        bytes32 indexed lotId,
        address indexed warehouse,
        uint256 indexed liquidationCycleId,
        uint256 carriedCollateral
    );
    event LotFacilityAssigned(
        bytes32 indexed lotId, uint256 indexed facilityId, uint256 principal, uint256 interest
    );
    event LotFacilityDebtRetired(
        bytes32 indexed lotId, uint256 indexed facilityId, uint256 principal, uint256 interest
    );
    /// @notice A V4 lot sale burns combined debt, then keeps surplus free; interestKept is zero.
    ///         principalBurned is the principal-origin part; FoldDebtSettled records the full burn.
    event LotSold(
        bytes32 indexed lotId,
        uint256 sold,
        uint256 proceeds,
        uint256 interestKept,
        uint256 principalBurned,
        uint256 tabRepaid,
        uint256 collateralLeft,
        uint256 principalLeft
    );
    event LotSaleNoFill(bytes32 indexed lotId, address indexed route, uint256 offered);
    /// @notice Marked shortfall recorded at takeover at the market price (0192). What is still marked is
    ///         min(this, the lot's principal): principal retires unmarked first.
    mapping(bytes32 lotId => uint256) public lotMarkedShortfall;
    event LotMarked(bytes32 indexed lotId, uint256 markedShortfall, uint256 price);
    /// @notice A lot sale or fold paid off `principal` of the lot's loan, freeing that much of its facility's
    ///         borrowing room (0195).
    event LotPrincipalRetired(bytes32 indexed lotId, uint256 indexed facilityId, uint256 principal);
    /// @notice The waterfall repaid `amount` of the pool's TAB from free jUSD (0197); the `TabRepaid` event in the
    ///         same transaction carries the balances after. `lastSettledCycleTabAfter` is the reporting figure of
    ///         0200 (see `SaleTabRepaid`).
    event WaterfallTabRepaid(
        uint256 indexed poolId, uint256 amount, uint256 lastSettledCycleTabAfter
    );
    /// @notice The waterfall repaired `amount` of a reserve's gap from free jUSD (0197); the reserve's own
    ///         `ReserveRepaired` event carries its balances after.
    event WaterfallReserveRepaired(address indexed asset, address indexed reserve, uint256 amount);
    error WaterfallBindingInvalid();
    /// @notice Waterfall step 1 (task 0201): one atomic round trip on the pool's own venues; `profit` = minted − spent
    ///         stays free (attributed to `SOURCE_ARBITRAGE`).
    event ArbitrageExecuted(
        uint256 indexed collateralId, uint256 indexed poolId, uint256 spent, uint256 minted
    );
    /// @notice Compatibility repayment event; lastSettledCycleTabAfter is a legacy BITE diagnostic, not a
    ///         liquidation-cycle balance. LiquidationCycleRecovery supplies the source-cycle attribution.
    ///         The pool continues to split repayments pro rata across units, queued claims and earnings.
    event SaleTabRepaid(uint256 indexed poolId, uint256 amount, uint256 lastSettledCycleTabAfter);
    /// @notice A stable sale migrates combined debt and mints only surplus; interestMinted is zero.
    ///         principalMigrated is the principal-origin part; FoldDebtSettled records the full migration.
    event LotFolded(
        bytes32 indexed lotId,
        address indexed asset,
        uint256 sold,
        uint256 backingIn,
        uint256 interestMinted,
        uint256 principalMigrated,
        uint256 surplusMinted,
        uint256 tabRepaid,
        uint256 collateralLeft,
        uint256 principalLeft
    );
    event LotFoldNoFill(
        bytes32 indexed lotId, address indexed asset, address executor, uint256 offered
    );

    /// @notice Newly minted recovery PRUSD awaiting classification within the current call (DEF-225).
    ///         Cleared once the mint has been allocated to repayment or reserved cycle cash. Repayment
    ///         may also use previously retained cash, so its amount does not decrement this tally.
    ///         Persistent cycle reserves are tracked separately and must not block the fold policy.
    mapping(uint256 poolId => uint256) public recoveryUnpaid;
    event InventoryRecoveryNoFill(
        uint256 indexed collateralId,
        uint256 indexed poolId,
        address indexed asset,
        address executor,
        uint256 offered
    );
    event InventoryRecovered(
        uint256 indexed collateralId,
        uint256 indexed poolId,
        address indexed asset,
        address reserve,
        uint256 sold,
        uint256 backingReceived,
        uint256 prusdMinted,
        uint256 tabRepaid,
        uint256 collateralRemaining
    );

    struct Recovery {
        uint256 cid;
        uint256 pid;
        uint256 sold;
        uint256 received;
        uint256 minted;
        uint256 repaid;
        uint256 revenuePaid;
        address pool;
        address reserve;
    }

    mapping(address => mapping(uint256 => bool)) public residualPurchased;
    /// @notice Treasury-booked residual obligation; becomes outstanding only at pool consumption.
    ///         Kept as cycle history, never added to outstanding twice.
    mapping(address => mapping(uint256 => uint256)) public residualTab;
    event WarehouseResidualPurchased(
        address indexed pool, uint256 indexed cycle, uint256 collateral, uint256 cash, uint256 tab
    );

    constructor(address admin, IPRUSD asset_) Treasury(admin, asset_) {
        SupportedChains.check();
    }

    /// @notice Bind the waterfall lane contract (task 0197), once.
    function setWaterfall(address w) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (waterfall != address(0) || w.code.length == 0) revert WaterfallBindingInvalid();
        waterfall = w;
    }

    /// @notice Waterfall step 1/2 (task 0197): repay up to `amount` of the pool's TAB from free jUSD. Sized here from
    ///         live figures (TAB owed, free jUSD), never trusted from the caller. Older TAB first. Returns what was
    ///         paid.
    function waterfallRepayTab(uint256 pid, uint256 amount)
        external
        nonReentrant
        returns (uint256 paid)
    {
        if (msg.sender != waterfall) revert WaterfallBindingInvalid();
        address pool = poolRegistry.getPool(pid).pool;
        if (pool == address(0)) revert ResidualMismatch();
        paid = Math.min(amount, Math.min(_freeCashRepayableTab(pid), spendableCash()));
        if (paid == 0) return 0;
        _debitOutflow(paid);
        _repayTab(pid, pool, paid, false);
        emit WaterfallTabRepaid(pid, paid, lastSettledCycleTab[pid].amount);
    }

    /// @notice Waterfall step 1 (task 0201): buy the collateral cheaply on the pool's admitted arbitrage route with at
    ///         most `min(spend, free PRUSD, the route's maximum)`, sell all of it on the admitted recovery route, mint
    ///         through the reserve and keep the profit free; reverts unless the mint beats the spend by the route's
    ///         minimum profit. The lane is the only door; the registry holds the route and its parameters.
    function arbitrage(
        uint256 cid,
        uint256 spend,
        address asset,
        address executor,
        bytes calldata data
    ) external nonReentrant returns (uint256 spent, uint256 minted) {
        if (msg.sender != waterfall) revert WaterfallBindingInvalid();
        _checkOutflow(0);
        uint256 pid;
        (pid, spent, minted) = TreasurySales.arbitrage(cid, spend, asset, executor, data);
        if (spent != 0) {
            _book(SOURCE_ARBITRAGE, minted - spent);
            emit ArbitrageExecuted(cid, pid, spent, minted);
        }
    }

    /// @dev Isolated rollback frame within recoverCollateral's reentrancy guard, never an operator entrypoint.
    function cycleArbitrage(
        uint256 cid,
        uint256 budget,
        address asset,
        address executor,
        bytes calldata data
    ) external returns (uint256 spent, uint256 minted) {
        if (msg.sender != address(this) || !_reentrancyGuardEntered()) {
            revert ResidualMismatch();
        }
        (spent, minted) = TreasurySales.cycleArbitrage(cid, budget, asset, executor, data);
        _book(SOURCE_ARBITRAGE, minted - spent);
    }

    /// @notice Waterfall step 3 (task 0197): repair up to `amount` of a reserve's gap from free jUSD. Sized here from
    ///         live figures (the gap, free jUSD). The reserve burns the jUSD; nothing is minted. Returns what was paid.
    function waterfallRepairReserve(address asset, uint256 amount)
        external
        nonReentrant
        returns (uint256 paid)
    {
        if (msg.sender != waterfall) revert WaterfallBindingInvalid();
        address reserve = reserveRegistry.reserveForAsset(asset);
        if (reserve == address(0)) revert ResidualMismatch();
        paid = Math.min(amount, Math.min(IRepairReserve(reserve).repairGap(), spendableCash()));
        if (paid == 0) return 0;
        uint256 beforeCash = prusd.balanceOf(address(this));
        _debitOutflow(paid);
        TreasurySales.payRepair(address(prusd), reserve, paid, beforeCash);
        emit WaterfallReserveRepaired(asset, reserve, paid);
    }

    function setReserveRegistry(address registry) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (address(reserveRegistry) != address(0)) revert ResidualMismatch();
        TreasurySales.checkReserveRegistry(registry, address(prusd), address(escapeRegistry));
        reserveRegistry = StableReserveRegistry(registry);
        emit ReserveRegistrySet(registry);
    }

    /// @notice One executable lot per liquidation cycle. Facility debt stays on chain; borrower
    ///         attribution is reconstructed from seizure and aggregate settlement events.
    /// @dev The existing linked library authenticates the canonical warehouse, measures custody,
    ///      and reclassifies only this cycle's carried collateral. Handover does not mint, burn,
    ///      pay interest or release facility capacity; subsequent settlement does.
    function assumeFoldedWarehouse(uint256 cid, LotHandover[] calldata handover)
        external
        nonReentrant
        returns (uint256 received)
    {
        if (_cow.externalCycle[cid] != 0) {
            address seller = _cow.sellerForCollateral[cid];
            _cowAction(TreasuryCow.Action(TreasuryCow.ActionKind.Return, seller, 0, 0, 0));
        }
        return TreasurySales.openAggregateLot(
            lots,
            _folds,
            lotMarkedShortfall,
            _liquidationCycles,
            seizedInventory,
            lotCollateral,
            foldedDebt,
            TreasurySales.FoldContext(
                address(vault),
                collateralRegistry,
                greaterMarket,
                cid,
                poolRegistry.poolForCollateral(cid),
                _cow.externalCollateral[cid]
            ),
            handover
        );
    }

    /// @notice Sell lot collateral through its SP's single route (the SP registry's sale route), at no worse than the
    ///         market price less the slippage tolerance (task 0191, DEF-245). A no-fill changes nothing.
    function sellLot(bytes32 id, uint256 offered, bytes calldata data)
        external
        returns (uint256 sold, uint256 proceeds)
    {
        return _instantLotSale(TreasuryFold.Sale(false, id, address(0), address(0), offered), data);
    }

    /// @notice SRV fold of lot collateral the V4 route did not take (task 0192): sell for a stablecoin through one of
    ///         the Treasury's recovery routes, then deposit into that stablecoin's reserve in the fold order.
    function foldLot(
        bytes32 id,
        address asset,
        address executor,
        uint256 offered,
        bytes calldata data
    ) external returns (uint256 sold, uint256 received) {
        return _instantLotSale(TreasuryFold.Sale(true, id, asset, executor, offered), data);
    }

    function _instantLotSale(TreasuryFold.Sale memory sale, bytes calldata data)
        private
        nonReentrant
        returns (uint256 sold, uint256 received)
    {
        _checkRole(Roles.HOTSWAP_ROLE);
        _checkOutflow(0);
        Lot storage lot = lots[sale.id];
        _checkLotAvailable(sale.id, lot.collateral, sale.offered);
        uint256 interest;
        uint256 surplus;
        (sold, received, interest, surplus) =
            TreasuryFold.sell(_folds, lot, lotCollateral, sale, data);
        if (sold != 0) {
            foldInterestReconciled += interest;
            _resolveExposure(lot.poolId, lot.collateralId, sold, surplus);
        }
    }

    function _checkLotAvailable(bytes32 id, uint256 collateral, uint256 offered) private view {
        if (offered == 0 || offered > collateral) revert ResidualMismatch();
        TreasuryCow.checkAvailable(_cow, id, collateral, offered);
    }

    /// @notice Move only an authenticated sold-out lot's remaining obligation to active reserves.
    function retryLotLoss(bytes32 id) external nonReentrant returns (uint256 accepted) {
        _checkOutflow(0);
        if (_cow.reserved[id] != 0) revert TreasuryCow.LotSettlementPending(id);
        if (lots[id].collateral != 0) revert TreasuryFold.InvalidLossSource();
        uint256 interest;
        (accepted, interest) = TreasuryFold.finalizeLoss(
            _folds, lots[id], id, address(vault), address(prusd), address(reserveRegistry)
        );
        foldInterestReconciled += interest;
    }

    /// @notice Role-gated compatibility path with a caller-selected maximum.
    function allocateLotLoss(bytes32 id, uint256 maximum)
        external
        nonReentrant
        returns (uint256 accepted)
    {
        _checkRole(Roles.HOTSWAP_ROLE);
        _checkOutflow(0);
        uint256 interest;
        if (_cow.reserved[id] != 0) revert TreasuryCow.LotSettlementPending(id);
        (accepted, interest) = TreasuryFold.allocateLoss(
            _folds, lots[id], id, address(vault), address(prusd), address(reserveRegistry), maximum
        );
        foldInterestReconciled += interest;
    }

    /// @dev Attribute `amount` of unattributed surplus to `source` (interest income, arbitrage profit).
    function _book(bytes32 source, uint256 amount) private {
        if (amount == 0) return;
        attributedInflows += amount;
        attributedBySource[source] += amount;
        emit RevenueRecorded(source, amount, attributedInflows);
    }

    function recoverCollateral(
        uint256 cid,
        uint256 liquidationCycle,
        address asset,
        address executor,
        uint256 offered,
        bytes calldata data
    )
        external
        nonReentrant
        returns (uint256 sold, uint256 backingReceived, uint256 minted, uint256 tabRepaid)
    {
        _checkOutflow(0); // An open revenue checkpoint must never count reserve issuance as revenue.
        Recovery memory r;
        r.cid = cid;
        r.pid = inventoryPoolId[cid];
        uint256 held = seizedInventory[cid];
        // Task 0294: next to a configured CoW seller a route may sell only what this contract still holds
        // itself: the cycle's collateral less its share at the seller, within the inventory not at sellers.
        uint256 outside = _cow.externalCycle[cid];
        // A missing pool or cycle has no recoverable collateral, so the bound below refuses it too.
        if (
            offered == 0 || offered + outside > held
                || offered > recoverableCycleCollateral(r.pid, liquidationCycle)
                || !allowedHotswapExecutor[executor]
        ) revert ResidualMismatch();
        outside += _cow.externalCollateral[cid]; // lots and cycles at sellers, for the custody identity
        (r.sold, r.received, r.minted, r.reserve, r.pool) = TreasurySales.recoverySale(
            settlementSource,
            TreasurySales.RecoverySale(
                address(reserveRegistry),
                cid,
                asset,
                executor,
                offered,
                held,
                lotCollateral[cid],
                outside
            ),
            data
        );
        if (r.sold == 0) {
            emit InventoryRecoveryNoFill(cid, r.pid, asset, executor, offered);
            return (0, 0, 0, 0);
        }
        _settleRecovery(r, liquidationCycle, asset, executor, data);
        return (r.sold, r.received, r.minted, r.repaid);
    }

    function _settleRecovery(
        Recovery memory r,
        uint256 liquidationCycle,
        address asset,
        address executor,
        bytes memory data
    ) private {
        seizedInventory[r.cid] -= r.sold;
        recoveryUnpaid[r.pid] += r.minted;
        (r.repaid, r.revenuePaid) = TreasurySales.recordCycleRecovery(
            _liquidationCycles,
            TreasurySales.CycleRecovery(
                r.pid,
                liquidationCycle,
                r.cid,
                r.sold,
                r.minted,
                poolLedger[r.pid].tabOutstanding,
                asset,
                executor
            ),
            data
        );
        if (r.repaid != 0) {
            attributedOutflows += r.revenuePaid;
            _repayTab(r.pid, r.pool, r.repaid, true);
        }
        // This transient tally does not include persistent, separately reserved cycle surplus.
        recoveryUnpaid[r.pid] -= r.minted;
        _finishRecovery(r, asset);
    }

    function _finishRecovery(Recovery memory r, address asset) private {
        _resolveExposure(r.pid, r.cid, r.sold, r.minted);
        _emitRecovery(r, asset);
    }

    /// @dev Pool-level purchase exposure is reporting, not TAB. Lot settlement passes only surplus:
    ///      paid interest and burned/migrated principal cannot also recover a previous purchase.
    function _resolveExposure(uint256 pid, uint256 cid, uint256 sold, uint256 recovered) private {
        uint256 resolved = Math.min(recovered, poolLedger[pid].unresolvedExposure);
        uint256 profit = recovered - resolved;
        if (profit > uint256(type(int256).max)) revert ResidualMismatch();
        _recordResolution(pid, cid, sold, recovered, int256(profit), resolved);
        _clearInventoryIfResolved(cid);
    }

    function _emitRecovery(Recovery memory r, address asset) private {
        emit InventoryRecovered(
            r.cid,
            r.pid,
            asset,
            r.reserve,
            r.sold,
            r.received,
            r.minted,
            r.repaid,
            seizedInventory[r.cid]
        );
    }

    /// @dev The caller has already classified the payment as current-cycle recovery or old-TAB waterfall.
    ///      Legacy last-bite diagnostics are clamped independently of cycle cash and recovery mints.
    ///      The caller books the revenue portion against the allocation funding this payment.
    function _repayTab(uint256 pid, address pool, uint256 amount, bool fromSale) private {
        uint256 beforeCash = prusd.balanceOf(address(this));
        _checkOutflow(amount);
        poolLedger[pid].tabOutstanding -= amount;
        totalTabOutstanding -= amount;
        _clampLastSettledCycleTab(pid, poolLedger[pid].tabOutstanding);
        poolLedger[pid].lastActivityAt = block.timestamp;
        TreasurySales.payRecovery(address(prusd), pool, amount, beforeCash);
        emit TabRepaid(
            pid, amount, poolLedger[pid].tabOutstanding, totalTabOutstanding, spendableCash()
        );
        if (fromSale) emit SaleTabRepaid(pid, amount, lastSettledCycleTab[pid].amount);
    }

    function _validateSettlementSource(address pool, address source) internal view override {
        TreasurySales.checkSettlementSource(address(vault), pool, source);
    }

    function _validateSettlementRecord(address pool, uint256 cycle, uint256 tab)
        internal
        view
        override
    {
        if (tab != residualTab[pool][cycle]) revert ResidualMismatch();
    }

    function purchaseWarehouseResidual() external nonReentrant returns (uint256 cash, uint256 tab) {
        TreasurySales.ResidualContext memory r = TreasurySales.residualContext(
            settlementSource, address(poolRegistry), address(vault), address(prusd)
        );
        address p = r.pool;
        uint256 pid = r.poolId;
        uint256 cid = r.collateralId;
        uint256 cycle = r.bite;
        uint256 amount = r.amount;
        if (residualPurchased[p][cycle] || settlements[p][cycle].state != SettlementState.None) {
            revert ResidualMismatch();
        }
        residualPurchased[p][cycle] = true;
        uint256 consideration =
            TreasurySales.receiveResidual(collateralRegistry, msg.sender, cid, amount, r.stop);
        // Residual BackstopBuy is TAB-only, irrespective of available Treasury cash.
        tab = consideration;
        _bindInventory(cid, pid, amount);
        _recordAdvance(pid, cid, cash, tab, consideration);
        residualTab[p][cycle] = tab;
        TreasurySales.recordCyclePurchase(
            _liquidationCycles, msg.sender, pid, cycle, amount, cash, tab
        );
        emit WarehouseResidualPurchased(p, cycle, amount, cash, tab);
    }
}

lib/openzeppelin-contracts/contracts/access/AccessControl.sol

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

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";

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

    mapping(bytes32 role => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

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

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

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

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

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

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

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

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

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

        _revokeRole(role, callerConfirmation);
    }

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

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

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

lib/openzeppelin-contracts/contracts/access/IAccessControl.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol

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

pragma solidity ^0.8.20;

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

lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

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

pragma solidity ^0.8.20;

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

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

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

pragma solidity ^0.8.20;

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

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

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

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

lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

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

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

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

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

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

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

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

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

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

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

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

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

lib/openzeppelin-contracts/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

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

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

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

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert Errors.FailedCall();
        }
    }

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/utils/Context.sol

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

pragma solidity ^0.8.20;

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

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

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

lib/openzeppelin-contracts/contracts/utils/Errors.sol

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

pragma solidity ^0.8.20;

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

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

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

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

lib/openzeppelin-contracts/contracts/utils/Panic.sol

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

pragma solidity ^0.8.20;

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

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

lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

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

    constructor() {
        _status = NOT_ENTERED;
    }

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

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

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

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

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

lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol

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

pragma solidity ^0.8.20;

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

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

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

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

pragma solidity ^0.8.20;

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

lib/openzeppelin-contracts/contracts/utils/math/Math.sol

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

pragma solidity ^0.8.20;

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

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

    /**
     * @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

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

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

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

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

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

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

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
            // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2²⁵⁶ + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

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

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

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

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

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

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

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

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

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

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        uint256 mLen = m.length;

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 exp;
        unchecked {
            exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
            value >>= exp;
            result += exp;

            exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
            value >>= exp;
            result += exp;

            exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
            value >>= exp;
            result += exp;

            exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
            value >>= exp;
            result += exp;

            exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
            value >>= exp;
            result += exp;

            exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
            value >>= exp;
            result += exp;

            exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
            value >>= exp;
            result += exp;

            result += SafeCast.toUint(value > 1);
        }
        return result;
    }

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

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

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

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 isGt;
        unchecked {
            isGt = SafeCast.toUint(value > (1 << 128) - 1);
            value >>= isGt * 128;
            result += isGt * 16;

            isGt = SafeCast.toUint(value > (1 << 64) - 1);
            value >>= isGt * 64;
            result += isGt * 8;

            isGt = SafeCast.toUint(value > (1 << 32) - 1);
            value >>= isGt * 32;
            result += isGt * 4;

            isGt = SafeCast.toUint(value > (1 << 16) - 1);
            value >>= isGt * 16;
            result += isGt * 2;

            result += SafeCast.toUint(value > (1 << 8) - 1);
        }
        return result;
    }

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

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

lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

            return true;
        } else {
            return false;
        }
    }

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

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

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

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

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }
}

src/StableReserveVault.sol

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

import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IPRUSD} from "./interfaces/IPRUSD.sol";
import {Roles} from "./libraries/Roles.sol";
import {TestDrain} from "./libraries/TestDrain.sol";
import {StableReserveMath} from "./libraries/StableReserveMath.sol";
import {ITreasury} from "./interfaces/ITreasury.sol";
import {RevenueSources} from "./libraries/RevenueSources.sol";

interface IReserveTreasuryIdentity {
    function prusd() external view returns (address);
    function executionActive() external view returns (bool);
}

/// @notice One external stable's custody and nominal PRUSD debt. Not an investor share vault.
/// @dev Treasury integration must authenticate operational proceeds before calling this contract.
///      No public mint, debt-migration setter, reserve sweep or administrative balance edit exists.
contract StableReserveVault is AccessControl, ReentrancyGuard {
    using SafeERC20 for IERC20;

    uint256 public constant REDEMPTION_FEE_BPS = 50;
    IERC20 public immutable backingAsset;
    IPRUSD public immutable prusd;
    address public immutable treasury;
    uint8 public immutable backingDecimals;

    uint256 public backing; // external-token base units; donations excluded
    uint256 public debt; // PRUSD base units (18 decimals)
    uint256 private _revenueNonce;

    error InvalidBinding();
    error ZeroAmount();
    error ReceiptMismatch();
    error CustodyDeficit();
    error OutputTooLow();
    error MigrationExceedsDeposit(uint256 unminted, uint256 value);
    error NotUnderwater();
    error RepairExceedsGap(uint256 amount, uint256 gap);
    error TreasuryExecutionActive();

    event ReserveDeposited(
        address indexed treasury,
        uint256 backingIn,
        uint256 prusdMinted,
        uint256 backingAfter,
        uint256 debtAfter
    );
    /// @notice Part of a deposit's value booked as migrated combined debt without minting.
    event ReserveDebtMigrated(
        address indexed treasury, uint256 migrated, uint256 backingAfter, uint256 debtAfter
    );
    /// @notice Waterfall repair (task 0197, Tim's guide §3 priority 3): the Treasury's PRUSD was burned and reserve
    ///         debt fell by exactly that; backing untouched.
    event ReserveRepaired(address indexed treasury, uint256 amount, uint256 debt, uint256 backing);
    event ReserveLossAccepted(
        address indexed treasury, uint256 amount, uint256 debt, uint256 backing
    );
    event ReserveRedeemed(
        address indexed caller,
        address indexed receiver,
        uint256 prusdBurned,
        uint256 grossBacking,
        uint256 netBacking,
        uint256 feeBacking,
        uint256 backingAfter,
        uint256 debtAfter
    );
    /// @notice Fee transferred in PRUSD, not burned. Separate from legacy backing-token fee evidence.
    event ReserveFeePaid(address indexed caller, uint256 feePrusd);

    constructor(IERC20 backingAsset_, IPRUSD prusd_, address treasury_) {
        if (
            address(backingAsset_).code.length == 0 || address(prusd_).code.length == 0
                || treasury_.code.length == 0 || address(backingAsset_) == address(prusd_)
                || treasury_ == address(backingAsset_) || treasury_ == address(prusd_)
                || IReserveTreasuryIdentity(treasury_).prusd() != address(prusd_)
                || IERC20Metadata(address(prusd_)).decimals() != 18
        ) revert InvalidBinding();
        uint8 decimals = IERC20Metadata(address(backingAsset_)).decimals();
        StableReserveMath.normalize(0, decimals); // validates the supported decimal range
        backingAsset = backingAsset_;
        prusd = prusd_;
        treasury = treasury_;
        backingDecimals = decimals;
        // No admin role: neither the deployer nor a wallet can add another mint caller.
        _grantRole(Roles.TREASURY_ROLE, treasury_);
    }

    /// @notice WH-08: received operational backing mints 1:1, including into an impaired reserve.
    function depositFromTreasury(uint256 amount)
        external
        onlyRole(Roles.TREASURY_ROLE)
        nonReentrant
        returns (uint256 minted)
    {
        minted = _deposit(amount, 0);
    }

    /// @notice Fold deposit: full value adds backing and debt; `unminted` migrates combined lot debt.
    ///         Only backing above that obligation mints surplus; no separate interest income is created.
    function depositFromTreasuryMigrating(uint256 amount, uint256 unminted)
        external
        onlyRole(Roles.TREASURY_ROLE)
        nonReentrant
        returns (uint256 minted)
    {
        minted = _deposit(amount, unminted);
        emit ReserveDebtMigrated(treasury, unminted, backing, debt);
    }

    /// @notice Authenticated folded obligation, not a deposit or issuance. Backing is untouched.
    function acceptLoss(uint256 amount) external onlyRole(Roles.TREASURY_ROLE) nonReentrant {
        if (amount == 0) revert ZeroAmount();
        _checkCustody();
        debt += amount;
        emit ReserveLossAccepted(treasury, amount, debt, backing);
    }

    /// @notice Reserve debt above its backing, in PRUSD units: what a waterfall repair can retire. Zero at or above
    ///         par.
    function repairGap() public view returns (uint256) {
        uint256 backed = StableReserveMath.normalize(backing, backingDecimals);
        return debt > backed ? debt - backed : 0;
    }

    /// @notice Waterfall repair (task 0197): pull `amount` PRUSD from the Treasury and burn it; debt falls by exactly
    ///         that, backing is untouched. Refused at or above par and beyond the gap. Treasury-only; the Treasury
    ///         sizes the amount from live figures.
    function repairFromTreasury(uint256 amount)
        external
        onlyRole(Roles.TREASURY_ROLE)
        nonReentrant
    {
        if (amount == 0) revert ZeroAmount();
        uint256 gap = repairGap();
        if (gap == 0) revert NotUnderwater();
        if (amount > gap) revert RepairExceedsGap(amount, gap);
        uint256 beforeSupply = prusd.totalSupply();
        uint256 beforeCash = prusd.balanceOf(treasury);
        IERC20(address(prusd)).safeTransferFrom(treasury, address(this), amount);
        prusd.burn(address(this), amount);
        if (
            prusd.totalSupply() != beforeSupply - amount
                || prusd.balanceOf(treasury) != beforeCash - amount
        ) revert ReceiptMismatch();
        debt -= amount;
        emit ReserveRepaired(treasury, amount, debt, backing);
    }

    function _deposit(uint256 amount, uint256 unminted) private returns (uint256 minted) {
        if (amount == 0) revert ZeroAmount();
        _checkCustody();
        uint256 value = StableReserveMath.normalize(amount, backingDecimals);
        if (unminted > value) revert MigrationExceedsDeposit(unminted, value);
        minted = value - unminted;
        uint256 beforeBacking = backingAsset.balanceOf(address(this));
        backingAsset.safeTransferFrom(treasury, address(this), amount);
        if (backingAsset.balanceOf(address(this)) != beforeBacking + amount) {
            revert ReceiptMismatch();
        }
        backing += amount;
        debt += value;
        if (minted != 0) {
            uint256 beforeCash = prusd.balanceOf(treasury);
            uint256 beforeSupply = prusd.totalSupply();
            prusd.mint(treasury, minted);
            if (
                prusd.balanceOf(treasury) != beforeCash + minted
                    || prusd.totalSupply() != beforeSupply + minted
            ) revert ReceiptMismatch();
        }
        _checkCustody();
        emit ReserveDeposited(treasury, amount, minted, backing, debt);
    }

    /// @notice Take the fee in PRUSD as Treasury revenue; burn only the rest for bounded backing units.
    function redeem(uint256 amount, uint256 minBackingOut, address receiver)
        external
        nonReentrant
        returns (uint256 net)
    {
        if (IReserveTreasuryIdentity(treasury).executionActive()) {
            revert TreasuryExecutionActive();
        }
        if (amount == 0) revert ZeroAmount();
        if (receiver == address(0) || receiver == address(this)) revert InvalidBinding();
        _checkCustody();
        uint256 fee;
        (, net, fee) = previewRedeem(amount);
        if (net == 0 || net < minBackingOut) revert OutputTooLow();
        uint256 burned = amount - fee;
        backing -= net;
        debt -= burned;

        uint256 beforeCash = prusd.balanceOf(address(this));
        uint256 beforeSupply = prusd.totalSupply();
        IERC20(address(prusd)).safeTransferFrom(msg.sender, address(this), amount);
        if (prusd.balanceOf(address(this)) != beforeCash + amount) revert ReceiptMismatch();
        prusd.burn(address(this), burned);
        // Reuse Treasury's measured checkpoint. Donations precede the snapshot and are excluded.
        bytes32 operation = keccak256(abi.encode(address(this), ++_revenueNonce));
        ITreasury(treasury).beginRecord(operation);
        IERC20(address(prusd)).safeTransfer(treasury, fee);
        ITreasury(treasury).finalizeRecord(operation, RevenueSources.FEE, fee);
        if (
            prusd.balanceOf(address(this)) != beforeCash
                || prusd.totalSupply() != beforeSupply - burned
        ) revert ReceiptMismatch();

        _transferBacking(receiver, net);
        _checkCustody();
        emit ReserveFeePaid(msg.sender, fee);
        emit ReserveRedeemed(msg.sender, receiver, burned, net, net, 0, backing, debt);
    }

    /// @notice Fee denomination; legacy reserves without this getter charge the backing asset.
    function redemptionFeeToken() external view returns (address) {
        return address(prusd);
    }

    function previewRedeem(uint256 amount)
        public
        view
        returns (uint256 gross, uint256 net, uint256 feePrusd)
    {
        return StableReserveMath.quoteRedemption(
            backing, debt, amount, backingDecimals, REDEMPTION_FEE_BPS
        );
    }

    function surplus() external view returns (uint256) {
        uint256 balance = backingAsset.balanceOf(address(this));
        return balance > backing ? balance - backing : 0;
    }

    function custodyDeficit() external view returns (uint256) {
        uint256 balance = backingAsset.balanceOf(address(this));
        return balance < backing ? backing - balance : 0;
    }

    function _checkCustody() private view {
        if (IERC20Metadata(address(backingAsset)).decimals() != backingDecimals) {
            revert InvalidBinding();
        }
        if (backingAsset.balanceOf(address(this)) < backing) revert CustodyDeficit();
    }

    function _transferBacking(address receiver, uint256 amount) private {
        if (amount == 0) return;
        uint256 beforeSender = backingAsset.balanceOf(address(this));
        uint256 beforeReceiver = backingAsset.balanceOf(receiver);
        backingAsset.safeTransfer(receiver, amount);
        if (
            backingAsset.balanceOf(address(this)) != beforeSender - amount
                || backingAsset.balanceOf(receiver) != beforeReceiver + amount
        ) revert ReceiptMismatch();
    }

    /// @notice Task 0300 test-deployment teardown: sends `amount` of `token` to the caller, no accounting update.
    ///         This contract has no role table; the Treasury's TEST_DRAIN_ROLE decides.
    function drain(address token, uint256 amount) external {
        TestDrain.requireTreasuryRole(treasury);
        TestDrain.send(token, amount);
    }
}

src/Treasury.sol

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

import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IPRUSD} from "./interfaces/IPRUSD.sol";
import {ITreasury} from "./interfaces/ITreasury.sol";
import {IStabilityPoolSettlementLedger} from "./interfaces/IStabilityPoolSettlementLedger.sol";
import {ISettlementExecutor} from "./interfaces/ISettlementExecutor.sol";
import {ISettlementPool7540} from "./interfaces/ISettlementPool7540.sol";
import {ICollateralRegistry} from "./interfaces/ICollateralRegistry.sol";
import {IStabilityPoolRegistry} from "./interfaces/IStabilityPoolRegistry.sol";
import {IOracleAdapter} from "./interfaces/IOracleAdapter.sol";
import {IGreaterMarketReference} from "./interfaces/IGreaterMarketReference.sol";
import {CollateralConfig, StabilityPoolInfo} from "./types/ProtocolTypes.sol";
import {PsmAsset} from "./registries/PsmAssetRegistry.sol";
import {Roles} from "./libraries/Roles.sol";
import {TestDrain} from "./libraries/TestDrain.sol";
import {RevenueSources} from "./libraries/RevenueSources.sol";
import {TreasurySales} from "./libraries/TreasurySales.sol";
import {SettlementProfit} from "./libraries/SettlementProfit.sol";
import {TreasuryFold} from "./libraries/TreasuryFold.sol";

/// @dev Minimal Vault operations for a Treasury-routed liquidation: preserve a recoverable borrower vault through
///      the facility's normal partial close, or assume the whole position when a safe partial is impossible.
interface IVaultBackstop {
    function owed(address owner, uint256 facilityId)
        external
        view
        returns (uint256 principal, uint256 interest);
    function prepareTreasuryLiquidation(address owner, uint256 facilityId)
        external
        returns (uint256 principalToClear, bool partialLiquidation);
    function liquidateToTreasury(address owner, uint256 facilityId)
        external
        returns (
            uint256 principal,
            uint256 interest,
            uint256 collateral,
            uint256 poolId,
            uint256 collateralId,
            uint256 gPriceUsed
        );
    function assumeVault(address owner, uint256 facilityId)
        external
        returns (
            uint256 principal,
            uint256 interest,
            uint256 collateral,
            uint256 poolId,
            uint256 collateralId,
            uint256 collateralRefunded,
            uint256 gPriceUsed
        );
}

/// @dev The escape-asset surface the Treasury needs from the PSM asset registry (0071) — the ONLY source of a
///      hotswap exit asset's eligibility, oracle, and depeg band. `getAsset` returns the zero struct for an
///      unlisted token (`enabled == false`), so an unknown/ineligible asset is rejected by the `escapeEnabled` gate.
interface IEscapeAssetRegistry {
    function getAsset(address token) external view returns (PsmAsset memory);
}

/// @notice Protocol revenue, custody and per-pool non-transferable TAB liability ledger.
/// @dev Outcomes require a set-once contract source. Legacy token settlement is removed.
contract Treasury is ITreasury, IStabilityPoolSettlementLedger, AccessControl, ReentrancyGuard {
    using SafeERC20 for IERC20;

    /// @notice Registry route administration may proceed only between guarded executions.
    function executionActive() external view returns (bool) {
        return _reentrancyGuardEntered();
    }

    /// @notice PRUSD — the only asset this Treasury holds/accounts in the basic sink (no PSM reserve yet).
    IPRUSD public immutable prusd;

    // ── Revenue attribution ledger (0058) ────────────────────────────────────────────────────────
    uint256 private constant BPS = 10_000;
    uint256 private constant PAR = 1e18; // $1 in oracle 18-dec terms — the escape-asset depeg reference (0071)

    bytes32 public constant SOURCE_FEE = RevenueSources.FEE;
    bytes32 public constant SOURCE_INTEREST = RevenueSources.INTEREST;
    bytes32 public constant SOURCE_LIQ_PROFIT = RevenueSources.LIQ_PROFIT;
    bytes32 public constant SOURCE_EARLY_EXIT_PENALTY = RevenueSources.EARLY_EXIT_PENALTY;
    bytes32 public constant SOURCE_ARBITRAGE = RevenueSources.ARBITRAGE;

    /// @notice Sum of all attributed inflows / outflows. `netAccounted = inflows − outflows` is protocol
    ///         revenue across free and reserved allocations. Unattributed cash also includes recovery proceeds;
    ///         it is not a donation ledger. `unattributed()` excludes both cash and revenue held in cycles.
    uint256 public attributedInflows;
    uint256 public attributedOutflows;
    /// @notice Attributed inflow per source tag. GROSS
    ///         lifetime by source — never debited on withdrawal (net-by-source is deferred; the enforced safety
    ///         invariant is the aggregate `netAccounted <= balance`).
    mapping(bytes32 source => uint256 amount) public attributedBySource;

    /// @notice Two-phase checkpoint (0058): a revenue source snapshots the Treasury's pre-transfer balance,
    ///         performs the mint/transfer, then finalizes — attribution binds to the MEASURED balance delta, so a
    ///         standing donation can't be swept and a fabricated op invents nothing. Only ONE checkpoint may be
    ///         open at a time (GLOBALLY): two checkpoints open across a shared balance change would each claim the
    ///         same delta (10 in, 20 attributed), so the two-phase is strictly serialized by `_open`.
    bool private _open;
    bytes32 private _openOp;
    uint256 private _openPre;
    mapping(bytes32 operationId => bool used) private _opUsed;

    error OperationInProgress(bytes32 openOperationId);
    error OperationAlreadyUsed(bytes32 operationId);
    error OperationNotStarted(bytes32 operationId);
    error DeltaMismatch(uint256 expected, uint256 actual);
    error InvalidSource(bytes32 source);

    // TREASURY_ASSUMPTION_LIMIT · Open · unset

    // ── Per-pool backstop ledger (0067) — ATTRIBUTION ONLY; shared balance, no siloing, no per-pool cap ──────
    // Records every Treasury backstop flow against the pool it helped/hurt so a dashboard can see which pool
    // contributes vs drains the Treasury and which exposure is stale. Primary key is `poolId` (collateralId is
    // 1:1 only on the current SingleAsset path — multi-asset SPs come later, so collateralId rides events as
    // metadata, never as the aggregation key). Written by the backstop (`BACKSTOP_ROLE`); moves no funds.
    struct PoolTreasuryLedger {
        uint256 prusdAdvanced;
        uint256 tabOutstanding;
        uint256 collateralReceivedValue;
        uint256 collateralSoldValue;
        int256 realizedPnL;
        uint256 unresolvedExposure;
        uint256 lastActivityAt;
    }

    mapping(uint256 poolId => PoolTreasuryLedger) public poolLedger;

    /// @notice The TAB given to each pool in the liquidation cycle it last settled, still unpaid — a reporting
    ///         figure (task 0200, Rule 0): the Treasury attributes every repayment to the pool's older TAB first, so
    ///         this only falls once no older TAB is left. It is an attribution label, not a payment order: the pool
    ///         splits each repayment pro rata across its units, queued claims and earnings TAB. A new settlement
    ///         replaces it, so unpaid TAB from the previous cycle becomes older TAB. Named apart from the pool's own
    ///         per-cycle `cycleTab` (DEF-248).
    struct CycleTab {
        uint256 cycle;
        uint256 amount;
    }

    mapping(uint256 poolId => CycleTab) public lastSettledCycleTab;

    // Global totals per tracked category — the invariant `Σ_pool == total<Category>` holds by construction.
    uint256 public totalPrusdAdvanced;
    uint256 public totalTabOutstanding;
    uint256 public totalCashFinalExitPenalties;
    uint256 public totalTabFinalExitPenalties;
    uint256 public totalCollateralReceivedValue;
    uint256 public totalCollateralSoldValue;
    int256 public totalRealizedPnL;
    uint256 public totalUnresolvedExposure;

    uint256[] private _ledgerPools; // enumerable set of pools with any ledger activity
    mapping(uint256 poolId => bool) private _ledgerPoolKnown;

    // ── BackstopBorrow (0068) — assume a whole unfundable vault into the interest-free Treasury debt facility ──
    IVaultBackstop public vault; // admin-wired (setVault), not a constructor immutable (avoids deploy ripple)
    // interest on assumed vaults — NEVER minted; tracked, not written off

    // ── Auto-hotswap / resolution (0068 slice 2; 0071 escape-asset set) — sell seized collateral into a keeper-
    // chosen ESCAPE ASSET, record the resolution. AUDITOR-HARDENED: the sale is BOUND to recorded seized inventory
    // (keyed by collateralId — never an arbitrary token, never more than held); the KEEPER picks the escape asset
    // (Treasury never claims to have found the globally best route) but the Treasury VERIFIES it — escape-eligible,
    // oracle valid + in the depeg band, executor allowlisted — and the floor is ORACLE-grounded (collateral USD →
    // selected asset, both decimals + oracles); only the MEASURED delta OF THE NAMED ASSET is booked, ledger stays
    // 18-dec USD. USDC is one eligible exit asset, NOT structurally privileged (0071). Fail-closed until wired.
    uint256 public constant MAX_HOTSWAP_SLIPPAGE_BPS = 1000; // 10% hard ceiling — never a give-away 100%
    ICollateralRegistry public collateralRegistry; // set-once — canonical token + oracle per collateralId
    IEscapeAssetRegistry public escapeRegistry; // set-once — PSM registry: escape eligibility + oracle + depeg band
    uint256 public hotswapSlippageBps; // HOTSWAP_SLIPPAGE_TOL (Open) — RISK_ADMIN; 0 ⇒ resolution fail-closed
    mapping(uint256 collateralId => uint256) public seizedInventory; // collateral warehoused, sellable via backstopResolve
    // SINGLE-ORIGIN binding (0084 Slice A, fail-closed): while `seizedInventory[cid] > 0`, ALL of a collateral's
    // warehouse inventory belongs to ONE originating pool. A DIFFERENT pool acquiring the same collateral is REVERTED
    // (never overwritten/commingled — that was the old single-slot bug). The binding clears only once the inventory
    // AND the bound pool's exposure are fully resolved, after which a later pool may bind. Weighted-average commingled
    // multi-pool accounting is task 0084 Slice B/C (decision-gated); this slice is deliberately fail-closed. (The
    // superseded FIFO draft is NOT the target; this is NOT the overwrite-prone single-slot behaviour either.)
    mapping(uint256 collateralId => uint256) public inventoryPoolId; // the ONE pool the warehoused inventory belongs to
    mapping(address executor => bool) public allowedHotswapExecutor;
    // realized forced-sale shortfall, still owed (earned back over time)
    // FORCED-sale floor: WAIVED (register WAREHOUSE_OFFLOAD_SLA, Locked 2026-08-03 — "at expiry sell at market,
    // tolerance waived"). Past the window the forced sale takes WHATEVER the governance-approved pool returns; the
    // Treasury enforces NO oracle floor on it. This does NOT reopen auditor HIGH-2 ("no floor + an ARBITRARY
    // executor"): the bound moved off the oracle onto EMERGENCY_ROLE (loss-accept multisig) + an allowlisted
    // approved-route executor (production `V4HotswapExecutor`, whose per-call `minOut` is the surviving execution
    // bound) + the measured-delta of the named asset. See docs/scenarios/backstop-resolution-and-hotswap.md §3.
    // Pool↔collateral 1:1 binding (auditor HIGH-3): resolution clears exposure at the POOL grain, but a sale
    // realizes ONE collateralId. On the SingleAsset path collateralId↔poolId is a bijection ("≤1 active pool per
    // collateral"); we ENFORCE it on-chain rather than silently assume it, so one collateral's forced clip can
    // never write off another collateral's debt. Reject a 2nd collateralId under a pool until per-collateral
    // exposure lands (multi-asset SPs).
    mapping(uint256 poolId => uint256) private _poolCollateral; // the single collateralId a pool's exposure is under
    mapping(uint256 poolId => bool) private _poolCollateralSet; // presence flag (collateralId 0 is a valid id)

    IStabilityPoolRegistry public poolRegistry;
    IGreaterMarketReference public greaterMarket;

    error CollateralRegistryNotSet();
    error CollateralRegistryAlreadySet();
    error EscapeRegistryNotSet();
    error EscapeRegistryAlreadySet();
    error EscapeAssetNotEligible(address escapeAsset);
    error EscapeAssetDepegged(address escapeAsset, uint256 price);
    error HotswapTokenIsEscapeAsset(address token);
    error HotswapSlippageNotSet();
    error HotswapSlippageTooHigh(uint256 bps, uint256 max);
    error HotswapWindowNotSet();
    error HotswapExecutorNotAllowed(address executor);
    error ExceedsSeizedInventory(uint256 collateralId, uint256 requested, uint256 available);
    error HotswapBelowFloor(uint256 proceedsRaw, uint256 floorInEscapeUnits);
    error NotYetForceable(uint256 collateralId, uint256 deadline);
    error OracleFloorZero(uint256 collateralId);
    error MultiAssetPoolUnsupported(
        uint256 poolId, uint256 boundCollateralId, uint256 newCollateralId
    );

    // ── BackstopBuy (0076) errors ──
    error PoolRegistryNotSet();
    error PoolRegistryAlreadySet();
    error SettlementTolNotSet();
    error SettlementTolTooHigh(uint256 bps, uint256 max);
    error NotRegisteredPool(address caller);
    error WrongCollateral(address expected, address got);
    // ── Greater-market reference (BACKSTOP_BUY_PRICE = G × (1 − TOL), task 0080 slice C) ──
    error GreaterMarketNotSet();
    error GreaterMarketAlreadySet();
    error GreaterMarketInvalid(uint256 collateralId);
    error ZeroFinalExitPenalty();
    error TokenReceiptMismatch(address token, uint256 expected, uint256 actual);
    error InsufficientSpendableCash(uint256 requested, uint256 available);
    error SettlementSourceInvalid();
    error SettlementSourceAlreadySet(address pool);
    error InvalidSettlementCycle(address pool, uint256 cycle);
    error TabLiabilityExceeded(uint256 requested, uint256 outstanding);

    // ── Single-origin warehouse binding (0084 Slice A, fail-closed) ──
    error InventoryOriginConflict(uint256 collateralId, uint256 boundPool, uint256 attemptedPool);

    event CollateralRegistrySet(address indexed registry);
    event EscapeRegistrySet(address indexed registry);
    event HotswapSlippageSet(uint256 bps);
    event HotswapExecutorSet(address indexed executor, bool allowed);
    event PoolRegistrySet(address indexed registry);
    event GreaterMarketReferenceSet(address indexed ref);
    error VaultNotSet();
    error VaultAlreadySet();
    error NothingToAssume(address borrower, uint256 facilityId);
    error AssumptionLimitExceeded(uint256 attempted, uint256 limit);
    error MintNotFullyCleared(uint256 minted, uint256 leftover); // net-zero self-check on the assumed-debt mint

    event VaultSet(address indexed vault);
    event RecordBegun(bytes32 indexed operationId, uint256 preBalance);
    event RevenueRecorded(bytes32 indexed source, uint256 amount, uint256 attributedInflows);
    event RecordCancelled(bytes32 indexed operationId);
    TreasurySales.BuybackBinding private _buyback;
    error BuybackBindingInvalid();
    event BuybackSet(address indexed buyback);
    event BuybackFunded(address indexed buyback, uint256 amount);

    // BackstopAdvanceRecorded / BackstopResolutionRecorded are declared on ITreasury (inherited) — the subgraph
    // seam. Do not redeclare here.

    /// @param admin Multisig/timelock-ready admin — holds DEFAULT_ADMIN and bootstraps the split operational roles
    ///        (HOTSWAP / BACKSTOP_OPERATOR, 0069) that governance then distributes to separate
    ///        wallets. No `tx.origin`.
    constructor(address admin, IPRUSD prusd_) {
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        // Operational trigger roles do not grant discretionary cash withdrawals.
        _grantRole(Roles.HOTSWAP_ROLE, admin);
        _grantRole(Roles.BACKSTOP_OPERATOR_ROLE, admin);
        prusd = prusd_;
    }

    // ════════════════════ Revenue receipt — attribution BOUND to a measured balance delta (0058) ════════════════════

    /// @notice Phase 1 of the fee/interest checkpoint: snapshot the Treasury's pre-transfer balance under
    ///         `operationId`. The caller (the Vault) then performs the mint/transfer and calls `finalizeRecord`,
    ///         all in ONE transaction, so the measured delta is causally the fee/interest ALONE.
    function beginRecord(bytes32 operationId) external onlyRole(Roles.REVENUE_SOURCE_ROLE) {
        if (_open) revert OperationInProgress(_openOp); // one checkpoint at a time — no shared-delta double-count
        if (_opUsed[operationId]) revert OperationAlreadyUsed(operationId);
        _open = true;
        _openOp = operationId;
        _openPre = _balance();
        emit RecordBegun(operationId, _openPre);
    }

    /// @notice Phase 2: require the measured balance delta since `beginRecord` equals `expectedAmount`, attribute
    ///         it to `source`, and consume the operation. A missing transfer (delta 0) or wrong amount reverts; a
    ///         standing donation sits inside `preBalance` and is excluded; the op can never be finalized twice.
    function finalizeRecord(bytes32 operationId, bytes32 source, uint256 expectedAmount)
        external
        onlyRole(Roles.REVENUE_SOURCE_ROLE)
    {
        if (!_open || operationId != _openOp) revert OperationNotStarted(operationId);
        if (source != SOURCE_FEE && source != SOURCE_INTEREST) revert InvalidSource(source); // fee/interest only
        uint256 delta = _balance() - _openPre;
        if (delta != expectedAmount) revert DeltaMismatch(expectedAmount, delta);
        _open = false;
        _openOp = bytes32(0);
        _opUsed[operationId] = true;
        attributedInflows += expectedAmount;
        attributedBySource[source] += expectedAmount;
        emit RevenueRecorded(source, expectedAmount, attributedInflows);
    }

    /// @notice EMERGENCY recovery for a checkpoint mistakenly left open ACROSS transactions — a same-tx
    ///         `finalizeRecord` failure already rolls `beginRecord` back, so this is only for an authorised source
    ///         that opened a checkpoint in a separate tx and never finalized. Clears ONLY the matching open
    ///         checkpoint, records the op consumed, attributes NOTHING. A stuck-open checkpoint would otherwise
    ///         block all recording (degrades safely — under-attribution, never fund loss).
    function cancelRecord(bytes32 operationId) external onlyRole(Roles.EMERGENCY_ROLE) {
        if (!_open || operationId != _openOp) revert OperationNotStarted(operationId);
        _open = false;
        _openOp = bytes32(0);
        _opUsed[operationId] = true;
        emit RecordCancelled(operationId);
    }

    /// @dev Shared measured-receipt primitive (0080 D1): pull `amount` of `token` from `from` and RETURN the MEASURED
    ///      balance delta — never trust the requested amount. `executeSale` asserts the delta equals the clip it
    ///      prices; `purchaseResidual` prices the returned delta. Phantom collateral can't be paid for (no approval ⇒
    ///      `transferFrom` reverts), donations are excluded (before/after bracket), fee-on-transfer is measured true.
    function _pullMeasured(address token, address from, uint256 amount)
        internal
        returns (uint256 received)
    {
        uint256 before = IERC20(token).balanceOf(address(this));
        IERC20(token).safeTransferFrom(from, address(this), amount);
        received = IERC20(token).balanceOf(address(this)) - before;
    }

    /// @dev Bind a collateral-in (BackstopBuy / residual / assume) to its ONE originating pool (0084 Slice A,
    ///      fail-closed). Fresh/cleared inventory binds to `poolId`; more from the SAME pool just adds; a DIFFERENT
    ///      pool while inventory remains REVERTS (never overwrite/commingle). A fresh offload window is stamped on the
    ///      (re)acquired collateral so it can't be force-sold below the floor before its NORMAL window (auditor MEDIUM-1).
    function _bindInventory(uint256 cid, uint256 poolId, uint256 amount) internal {
        uint256 held = seizedInventory[cid];
        uint256 origin = inventoryPoolId[cid];
        if (
            origin != 0 && origin != poolId
                && (held != 0 || poolLedger[origin].unresolvedExposure != 0)
        ) {
            revert InventoryOriginConflict(cid, origin, poolId);
        }
        inventoryPoolId[cid] = poolId;
        seizedInventory[cid] = held + amount;
    }

    /// @dev After a resolution, clear the single-origin binding ONLY once the inventory AND the bound pool's exposure
    ///      are fully resolved (0084 Slice A bullet 5) — so a later pool may safely bind. Conservative on purpose:
    ///      residual exposure keeps the binding (never rebinds mid-resolution). `poolLedger[0]` reads 0, so a call
    ///      with no binding is a no-op.
    function _clearInventoryIfResolved(uint256 cid) internal {
        uint256 boundPool = inventoryPoolId[cid];
        if (
            boundPool != 0 && seizedInventory[cid] == 0
                && poolLedger[boundPool].unresolvedExposure == 0
        ) {
            inventoryPoolId[cid] = 0;
        }
    }

    // ═══════════════ Per-pool backstop ledger (0067) — attribution only, BACKSTOP_ROLE writes it ═══════════════

    /// @dev Acquisition attribution only: gross exposure includes deferred consideration, but this helper never
    ///      credits TAB outstanding. Settlement consumption owns that credit. No public advance writer exists.
    function _recordAdvance(
        uint256 poolId,
        uint256 collateralId,
        uint256 prusdAdvanced_,
        uint256 deferredConsideration_,
        uint256 collateralReceivedValue_
    ) internal {
        _bindPoolCollateral(poolId, collateralId);
        _enrollPool(poolId);
        PoolTreasuryLedger storage l = poolLedger[poolId];
        l.prusdAdvanced += prusdAdvanced_;
        l.collateralReceivedValue += collateralReceivedValue_;
        uint256 exposure = prusdAdvanced_ + deferredConsideration_;
        l.unresolvedExposure += exposure;
        l.lastActivityAt = block.timestamp;
        totalPrusdAdvanced += prusdAdvanced_;
        totalCollateralReceivedValue += collateralReceivedValue_;
        totalUnresolvedExposure += exposure;
        emit BackstopAdvanceRecorded(
            poolId,
            collateralId,
            prusdAdvanced_,
            0, // acquisition creates exposure, not issued TAB; SettlementConsumed emits the later credit
            collateralReceivedValue_,
            l.unresolvedExposure,
            block.timestamp
        );
    }

    function _recordResolution(
        uint256 poolId,
        uint256 collateralId,
        uint256 collateralSoldValue_,
        uint256 reserveRecovered_,
        int256 realizedPnL_,
        uint256 exposureResolved_
    ) internal {
        _enrollPool(poolId);
        PoolTreasuryLedger storage l = poolLedger[poolId];
        uint256 cleared =
            exposureResolved_ < l.unresolvedExposure ? exposureResolved_ : l.unresolvedExposure;
        l.collateralSoldValue += collateralSoldValue_;
        l.realizedPnL += realizedPnL_;
        l.unresolvedExposure -= cleared;
        l.lastActivityAt = block.timestamp;
        totalCollateralSoldValue += collateralSoldValue_;
        totalRealizedPnL += realizedPnL_;
        totalUnresolvedExposure -= cleared;
        emit BackstopResolutionRecorded(
            poolId,
            collateralId,
            collateralSoldValue_,
            reserveRecovered_,
            realizedPnL_,
            l.unresolvedExposure,
            block.timestamp
        );
    }

    function _enrollPool(uint256 poolId) private {
        if (!_ledgerPoolKnown[poolId]) {
            _ledgerPoolKnown[poolId] = true;
            _ledgerPools.push(poolId);
        }
    }

    /// @dev Bind a pool to exactly one collateralId (auditor HIGH-3 / MEDIUM-2). Resolution clears exposure at the
    ///      POOL grain, so every advance that raises a pool's exposure must be for the SAME collateral — else one
    ///      collateral's forced-final clip would write off another's still-backed exposure. Enforced at the single
    ///      exposure-raising choke point (`_recordAdvance`), so it covers BOTH `backstopAssumeVault` AND the external
    ///      `recordBackstopAdvance` (BackstopBuy, slice 3). SingleAsset today ("≤1 active pool per collateral").
    function _bindPoolCollateral(uint256 poolId, uint256 collateralId) private {
        if (_poolCollateralSet[poolId]) {
            if (_poolCollateral[poolId] != collateralId) {
                revert MultiAssetPoolUnsupported(poolId, _poolCollateral[poolId], collateralId);
            }
        } else {
            _poolCollateralSet[poolId] = true;
            _poolCollateral[poolId] = collateralId;
        }
    }

    // Rules-controlled funding; arbitrary-recipient withdrawal was removed in 0329.
    /// @notice Deployment wiring only: bind the rules-controlled buyback once, as with the waterfall.
    function setBuyback(address b) external onlyRole(DEFAULT_ADMIN_ROLE) {
        TreasurySales.bindBuyback(_buyback, b, address(prusd));
    }

    function buyback() external view returns (address) {
        return _buyback.target;
    }

    /// @notice Only the bound buyback can fund its atomic purchase. There is no caller-chosen recipient.
    function fundBuyback(uint256 amount) external nonReentrant {
        _debitOutflow(amount);
        TreasurySales.payBuyback(_buyback, address(prusd), amount);
    }

    /// @notice Task 0300 test-deployment teardown: sends `amount` of `token` to the caller, no accounting update.
    function drain(address token, uint256 amount) external onlyRole(Roles.TEST_DRAIN_ROLE) {
        TestDrain.send(token, amount);
    }

    /// @dev Free-cash outflows consume free unattributed cash before free revenue. Reserved cycle revenue
    ///      cannot be debited here; cycle-funded payments classify their own revenue separately (0237).
    ///      MUST run BEFORE the transfer so failure rolls the accounting back atomically.
    function _debitOutflow(uint256 amount) internal {
        uint256 surplus = _freeUnattributed(_checkOutflow(amount));
        if (amount > surplus) attributedOutflows += amount - surplus;
    }

    /// @dev Spend authorization is independent of revenue attribution, including pass-through escrow.
    function _checkOutflow(uint256 amount) internal view returns (uint256 available) {
        if (_open) revert OperationInProgress(_openOp);
        available = spendableCash();
        if (amount > available) revert InsufficientSpendableCash(amount, available);
    }

    /// @notice Recognized revenue held outside the free Treasury allocation. Part of netAccounted, not extra cash.
    function reservedRevenue() public view virtual returns (uint256) {
        return 0;
    }

    // ════════════════════════ Views ════════════════════════

    /// @notice Protocol revenue held = attributed inflows net of attributed outflows (floored at 0).
    function netAccounted() public view returns (uint256) {
        return attributedInflows > attributedOutflows ? attributedInflows - attributedOutflows : 0;
    }

    /// @notice Free unattributed cash = spendable cash minus free recognized revenue, floored at zero.
    function unattributed() external view returns (uint256) {
        return _freeUnattributed(spendableCash());
    }

    function _freeUnattributed(uint256 bal) private view returns (uint256) {
        uint256 net = netAccounted() - reservedRevenue();
        return bal > net ? bal - net : 0;
    }

    /// @notice Count of pools with any backstop-ledger activity — dashboard enumeration + the Σ-invariant sum.
    function ledgerPoolCount() external view returns (uint256) {
        return _ledgerPools.length;
    }

    /// @notice The poolId at enumeration index `i`.
    function ledgerPoolAt(uint256 i) external view returns (uint256) {
        return _ledgerPools[i];
    }

    /// @dev The Treasury's own PRUSD balance — the ground truth every attribution rule measures against.
    function _balance() private view returns (uint256) {
        return IERC20(address(prusd)).balanceOf(address(this));
    }

    /// @notice Wire the canonical Vault seam ONCE, by governance (DEFAULT_ADMIN — multisig/timelock at deploy).
    ///         Set-once + immutable-after: the assumed-debt mint path trusts this counterparty, so it must not be
    ///         swappable by the day-to-day operator (`BACKSTOP_OPERATOR_ROLE`). Fixes the mutable/unverified-counterparty
    ///         mint risk.
    function setVault(IVaultBackstop vault_) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (address(vault) != address(0)) revert VaultAlreadySet();
        if (address(vault_) == address(0)) revert VaultNotSet();
        vault = vault_;
        emit VaultSet(address(vault_));
    }

    // ═══════════════ BackstopBuy (0076) — the Treasury as the SP's ISettlementExecutor ═══════════════

    /// @notice Wire the canonical StabilityPoolRegistry ONCE (DEFAULT_ADMIN) — the ONLY source of truth
    ///         `executeSale` authenticates the calling pool against. Never derived from caller-supplied data.
    function setPoolRegistry(IStabilityPoolRegistry registry)
        external
        onlyRole(DEFAULT_ADMIN_ROLE)
    {
        if (address(poolRegistry) != address(0)) {
            revert PoolRegistryAlreadySet();
        }
        if (address(registry) == address(0)) revert PoolRegistryNotSet();
        poolRegistry = registry;
        emit PoolRegistrySet(address(registry));
    }

    /// @notice Wire the canonical greater-market reference `G` the BackstopBuy prices off (0080 slice C) — set-once,
    ///         `DEFAULT_ADMIN`, fail-closed at zero. Mirrors `setPoolRegistry`. Until it is set, `executeSale` fails
    ///         closed. Interim it is a `GreaterMarketReferenceStub`; task 0081 swaps the real composite in.
    function setGreaterMarketReference(address ref) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (address(greaterMarket) != address(0)) revert GreaterMarketAlreadySet();
        if (ref == address(0) || ref.code.length == 0) revert GreaterMarketNotSet();
        greaterMarket = IGreaterMarketReference(ref);
        emit GreaterMarketReferenceSet(ref);
    }

    enum SettlementState {
        None,
        Ready,
        Consumed
    }

    struct Settlement {
        uint256 absorbedDebt;
        uint256 cash;
        uint256 tab;
        SettlementState state;
    }
    mapping(address pool => address source) public settlementSource;
    mapping(address pool => mapping(uint256 cycle => Settlement)) public settlements;
    uint256 public totalSettlementCashReserved;
    uint256 public totalSettlementCashPaid;

    event SettlementSourceSet(uint256 indexed poolId, address indexed pool, address indexed source);
    event SettlementRecorded(
        uint256 indexed poolId,
        uint256 indexed cycle,
        address indexed source,
        uint256 absorbedDebt,
        uint256 cash,
        uint256 tab,
        uint256 reservedCashAfter
    );
    event SettlementConsumed(
        uint256 indexed poolId,
        uint256 indexed cycle,
        uint256 cash,
        uint256 tab,
        uint256 outstandingAfter,
        uint256 totalOutstandingAfter,
        uint256 reservedCashAfter
    );
    event TabRepaid(
        uint256 indexed poolId,
        uint256 amount,
        uint256 outstandingAfter,
        uint256 totalOutstandingAfter,
        uint256 spendableCashAfter
    );
    // Historical event field names are retained for indexer compatibility; IOU here is ledger TAB, not a token.
    event FinalExitPenaltyReceived(
        uint256 indexed poolId,
        uint256 indexed collateralId,
        uint256 cashAmount,
        uint256 iouAmount,
        uint256 totalCashReceivedAfter,
        uint256 totalIouReceivedAfter,
        uint256 outstandingIouAfter,
        uint256 unresolvedExposureAfter
    );

    /// @notice Set-once contract authority, not an operational EOA. Unset until warehouse integration is audited.
    function setSettlementSource(address pool, address source)
        external
        onlyRole(DEFAULT_ADMIN_ROLE)
    {
        uint256 pid = _settlementPoolId(pool);
        if (source.code.length == 0 || source == pool || source == address(this)) {
            revert SettlementSourceInvalid();
        }
        if (settlementSource[pool] != address(0)) revert SettlementSourceAlreadySet(pool);
        _validateSettlementSource(pool, source);
        settlementSource[pool] = source;
        emit SettlementSourceSet(pid, pool, source);
    }

    /// @dev Concrete settlement integrations must validate their canonical source capability.
    function _validateSettlementSource(address, address) internal view virtual {}

    /// @notice Record a completed warehouse outcome and escrow its measured cash.
    /// @dev The bound warehouse MUST derive cash/TAB from execution, not forward keeper amounts.
    ///      Authorization, escrow and replay protection are provided here, not warehouse pricing.
    function recordSettlement(address pool, uint256 cycle, uint256 debt, uint256 cash, uint256 tab)
        external
        nonReentrant
    {
        if (_open) revert OperationInProgress(_openOp);
        if (msg.sender != settlementSource[pool]) revert SettlementSourceInvalid();
        (uint256 pid,) = TreasuryFold.validateSettlementCycle(
            address(poolRegistry), pool, address(prusd), cycle, debt, false
        );
        if (settlements[pool][cycle].state != SettlementState.None) {
            revert InvalidSettlementCycle(pool, cycle);
        }
        _validateSettlementRecord(pool, cycle, tab);
        settlements[pool][cycle] = Settlement(debt, cash, tab, SettlementState.Ready);
        if (cash != 0) {
            uint256 received = _pullMeasured(address(prusd), msg.sender, cash);
            if (received != cash) revert TokenReceiptMismatch(address(prusd), cash, received);
            totalSettlementCashReserved += cash;
        }
        emit SettlementRecorded(
            pid, cycle, msg.sender, debt, cash, tab, totalSettlementCashReserved
        );
    }

    /// @dev Extensions may bind TAB to obligations independently recorded during residual purchase.
    function _validateSettlementRecord(address, uint256, uint256) internal view virtual {}

    event SettlementProfitSplit(
        uint256 indexed poolId,
        uint256 indexed cycle,
        uint256 indexed liquidationCycleId,
        uint256 cashCut,
        uint256 tabCut,
        uint256 currentCycleTabAfter
    );

    /// @dev Return gross evidence for the pool's exact-match check; deliver and book net proceeds.
    function consumeSettlement(uint256 cycle, uint256 debt)
        external
        nonReentrant
        returns (uint256 grossCash, uint256 grossTab)
    {
        if (_open) revert OperationInProgress(_openOp);
        (uint256 pid, uint256 collateralId) = TreasuryFold.validateSettlementCycle(
            address(poolRegistry), msg.sender, address(prusd), cycle, debt, true
        );
        Settlement storage s = settlements[msg.sender][cycle];
        if (s.state != SettlementState.Ready || s.absorbedDebt != debt) {
            revert InvalidSettlementCycle(msg.sender, cycle);
        }
        grossCash = s.cash;
        grossTab = s.tab;
        (uint256 cashCut, uint256 tabCut) = SettlementProfit.cuts(debt, grossCash, grossTab);
        uint256 netCash = grossCash - cashCut;
        uint256 netTab = grossTab - tabCut;
        s.state = SettlementState.Consumed;
        totalSettlementCashReserved -= grossCash;
        _enrollPool(pid);
        _bindPoolCollateral(pid, collateralId);
        PoolTreasuryLedger storage l = poolLedger[pid];
        // Resale may already have resolved exposure; preserve the legacy capped reduction.
        uint256 exposureCut = tabCut < l.unresolvedExposure ? tabCut : l.unresolvedExposure;
        l.unresolvedExposure -= exposureCut;
        totalUnresolvedExposure -= exposureCut;
        l.tabOutstanding += netTab;
        lastSettledCycleTab[pid] = CycleTab(cycle, netTab);
        l.lastActivityAt = block.timestamp;
        totalTabOutstanding += netTab;
        totalSettlementCashPaid += netCash;
        if (cashCut != 0) {
            attributedInflows += cashCut;
            attributedBySource[SOURCE_LIQ_PROFIT] += cashCut;
            emit RevenueRecorded(SOURCE_LIQ_PROFIT, cashCut, attributedInflows);
        }
        if (cashCut != 0 || tabCut != 0) {
            (uint256 liquidationCycle, uint256 currentTab) = _settlementProfitTab(pid, tabCut);
            emit SettlementProfitSplit(pid, cycle, liquidationCycle, cashCut, tabCut, currentTab);
        }
        if (netCash != 0) {
            _checkOutflow(netCash);
            IERC20(address(prusd)).safeTransfer(msg.sender, netCash);
        }
        emit SettlementConsumed(
            pid,
            cycle,
            netCash,
            netTab,
            l.tabOutstanding,
            totalTabOutstanding,
            totalSettlementCashReserved
        );
    }

    /// @dev Warehouse Treasury also retires this bite's cut from the current liquidation-cycle TAB.
    function _settlementProfitTab(uint256, uint256)
        internal
        virtual
        returns (uint256 liquidationCycle, uint256 currentTab)
    {}

    /// @notice Receive exact penalty cash and retire only the calling pool's non-transferable liability.
    function receiveFinalExitPenalty(uint256 cash, uint256 tab) external nonReentrant {
        if (_open) revert OperationInProgress(_openOp);
        if (cash == 0 && tab == 0) revert ZeroFinalExitPenalty();
        uint256 pid = _settlementPoolId(msg.sender);
        PoolTreasuryLedger storage l = poolLedger[pid];
        if (tab > l.tabOutstanding) revert TabLiabilityExceeded(tab, l.tabOutstanding);
        l.tabOutstanding -= tab;
        totalTabOutstanding -= tab;
        _clampLastSettledCycleTab(pid, l.tabOutstanding);
        totalTabFinalExitPenalties += tab;
        l.lastActivityAt = block.timestamp;
        if (cash != 0) {
            uint256 received = _pullMeasured(address(prusd), msg.sender, cash);
            if (received != cash) revert TokenReceiptMismatch(address(prusd), cash, received);
            attributedInflows += cash;
            attributedBySource[SOURCE_EARLY_EXIT_PENALTY] += cash;
            totalCashFinalExitPenalties += cash;
            emit RevenueRecorded(SOURCE_EARLY_EXIT_PENALTY, cash, attributedInflows);
        }
        emit FinalExitPenaltyReceived(
            pid,
            ISettlementPool7540(msg.sender).collateralId(),
            cash,
            tab,
            totalCashFinalExitPenalties,
            totalTabFinalExitPenalties,
            l.tabOutstanding,
            l.unresolvedExposure
        );
    }

    /// @dev Compatibility clamp for the last settled BITE, not liquidation-cycle attribution.
    ///      WarehouseTreasury separately tracks current liquidation-cycle TAB (0219).
    function _clampLastSettledCycleTab(uint256 pid, uint256 total) internal virtual {
        if (lastSettledCycleTab[pid].amount > total) lastSettledCycleTab[pid].amount = total;
    }

    function _freeCashRepayableTab(uint256 pid) internal view virtual returns (uint256) {
        return poolLedger[pid].tabOutstanding;
    }

    function outstanding(address pool) external view returns (uint256) {
        if (address(poolRegistry) == address(0)) return 0;
        uint256 pid = poolRegistry.poolIdForPool(pool);
        return pid == 0 ? 0 : poolLedger[pid].tabOutstanding;
    }

    function spendableCash() public view virtual returns (uint256) {
        uint256 balance = _balance();
        return balance > totalSettlementCashReserved ? balance - totalSettlementCashReserved : 0;
    }

    function _settlementPoolId(address pool) private view returns (uint256 pid) {
        return TreasurySales.settlementPoolId(address(poolRegistry), pool, address(prusd));
    }

    // ═══════════════ Auto-hotswap / resolution (0068 slice 2) — governance wiring + the bound, oracle-floored sell

    /// @notice Wire the canonical CollateralRegistry ONCE (DEFAULT_ADMIN) — the ONLY source of the token + oracle
    ///         per collateralId used to price a resolution (never a caller input).
    function setCollateralRegistry(ICollateralRegistry registry)
        external
        onlyRole(DEFAULT_ADMIN_ROLE)
    {
        if (address(collateralRegistry) != address(0)) {
            revert CollateralRegistryAlreadySet();
        }
        if (address(registry) == address(0)) revert CollateralRegistryNotSet();
        collateralRegistry = registry;
        emit CollateralRegistrySet(address(registry));
    }

    /// @notice Wire the PSM asset registry ONCE (DEFAULT_ADMIN) — the ONLY source of escape-asset eligibility,
    ///         oracle, and depeg band for the hotswap (0071). Replaces the old single `reserveAsset`: USDC is one
    ///         eligible exit asset, not structurally privileged. PRUSD can never be an escape asset — it is never
    ///         admitted to the PSM asset registry (`PsmAssetRegistry`).
    function setEscapeRegistry(IEscapeAssetRegistry registry)
        external
        onlyRole(DEFAULT_ADMIN_ROLE)
    {
        if (address(escapeRegistry) != address(0)) {
            revert EscapeRegistryAlreadySet();
        }
        if (address(registry) == address(0)) revert EscapeRegistryNotSet();
        escapeRegistry = registry;
        emit EscapeRegistrySet(address(registry));
    }

    /// @notice `HOTSWAP_SLIPPAGE_TOL` (Open) — RISK_ADMIN governance, CAPPED at `MAX_HOTSWAP_SLIPPAGE_BPS`; `0`
    ///         keeps resolution fail-closed until set.
    function setHotswapSlippageBps(uint256 bps) external onlyRole(Roles.RISK_ADMIN_ROLE) {
        if (bps > MAX_HOTSWAP_SLIPPAGE_BPS) {
            revert HotswapSlippageTooHigh(bps, MAX_HOTSWAP_SLIPPAGE_BPS);
        }
        hotswapSlippageBps = bps;
        emit HotswapSlippageSet(bps);
    }

    /// @notice Allowlist a vetted sale venue for the hotswap (RISK_ADMIN governance).
    function setHotswapExecutor(address executor, bool allowed)
        external
        onlyRole(Roles.RISK_ADMIN_ROLE)
    {
        allowedHotswapExecutor[executor] = allowed;
        emit HotswapExecutorSet(executor, allowed);
    }
}

src/WarehouseSourceAuth.sol

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

import {IWarehouseRegistry} from "./interfaces/IWarehouseRegistry.sol";

interface IWarehouseVaultBinding {
    function warehouseRegistry() external view returns (address);
}

interface IWarehouseTreasuryBinding {
    function vault() external view returns (address);
    function settlementSource(address pool) external view returns (address);
}

library WarehouseSourceAuth {
    function canonical(address treasury, uint256 collateralId) internal view returns (address) {
        address vault = IWarehouseTreasuryBinding(treasury).vault();
        return canonicalFromVault(vault, collateralId);
    }

    function canonicalFromVault(address vault, uint256 collateralId)
        internal
        view
        returns (address)
    {
        address registry = IWarehouseVaultBinding(vault).warehouseRegistry();
        return IWarehouseRegistry(registry).warehouseForCollateral(collateralId);
    }
}

src/interfaces/IArbBuyer.sol

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

/// @title IArbBuyer — the buy leg of waterfall step 1 (task 0201): buys the collateral on the pool's own sale venue
///        with PRUSD, never above a ceiling price. The Treasury transfers `prusdOffered` here, then calls
///        `buyAtCeiling`; the buyer spends as much as clears at or below `ceilingC` (PRUSD-18dec per WHOLE
///        collateral), sends the collateral bought and the unspent PRUSD back to the caller, and returns what it did.
/// @notice Return values are ADVISORY: the Treasury books only its own measured balance deltas and reverts on a
///         mismatch. The V4 implementation proves a partial fill hit the ceiling from the pool's post-swap price.
interface IArbBuyer {
    /// @notice The warehouse this venue serves; only that warehouse's Treasury may buy.
    function pool() external view returns (address);
    function prusd() external view returns (address);
    function collateral() external view returns (address);
    function buyAtCeiling(
        address collateralToken,
        uint256 prusdOffered,
        uint256 ceilingC,
        bytes calldata data
    ) external returns (uint256 spent, uint256 returned, uint256 bought);
}

src/interfaces/ICollateralRegistry.sol

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

import {CollateralConfig} from "../types/ProtocolTypes.sol";

/// @notice Approved collateral assets and their oracle envelope. Does NOT define borrow products.
interface ICollateralRegistry {
    event CollateralRegistered(uint256 indexed collateralId, address indexed token, uint8 decimals);
    event CollateralEnabledSet(uint256 indexed collateralId, bool enabled);

    function getCollateral(uint256 collateralId) external view returns (CollateralConfig memory);
    function collateralIdForToken(address token) external view returns (uint256);
    function isEnabled(uint256 collateralId) external view returns (bool);
}

src/interfaces/IFloorSettlementExecutor.sol

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

/// @title IFloorSettlementExecutor — a settlement venue that sells the max collateral clearing at/above a floor
///        (task 0080 slice D). The SP hands it the whole seized clip and a floor price `F` (`settlementFloor(cid)`,
///        18-dec/whole-token); the executor sells as much as clears at `≥ F`, sends the PRUSD proceeds to the SP,
///        and RETURNS the unconsumed collateral to the SP.
/// @notice ⚠️ Return values are ADVISORY. The SP books `consumed`/`returned`/`proceeds` from its OWN measured balance
///         deltas — a lying/buggy executor cannot mis-book (a measurement mismatch reverts the whole settlement).
///         The REAL V4 executor (D2) additionally PROVES a partial fill hit the floor from post-swap pool state; the
///         D1 mock is not required to. Whichever it is, the SP/Treasury accounting is identical.
interface IFloorSettlementExecutor {
    function pool() external view returns (address);

    function prusd() external view returns (address);

    function collateral() external view returns (address);

    function executeAtFloor(
        address collateralToken,
        uint256 collateralOffered,
        uint256 floorF,
        bytes calldata data
    ) external returns (uint256 consumed, uint256 returned, uint256 proceeds);
}

src/interfaces/IGreaterMarketReference.sol

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

/// @title IGreaterMarketReference — the canonical collateral/USD market reference `G` (task 0080/0081).
/// @notice One manipulation-resistant `G(collateralId)` that seizure sizing (`X = debt×(1+bonus)/G`), the SP
///         marginal execution boundary (`F = G×(1−SLIPPAGE_TOL)`), and the Treasury exact-residual purchase price
///         all read — so every consumer prices off the SAME value/provenance at a block, never a divergent sample.
///
///         Contract: `priceUsd18` is an 18-decimal collateral/USD price. `valid == false` means the reference is
///         unavailable (unset / stale / below-quorum / manipulated) and the CONSUMER MUST FAIL CLOSED — never
///         substitute a caller-supplied price, a raw local spot, or a last-known-good value. Collateral-decimal
///         normalization is the consumer's responsibility, not this seam's.
///
///         The manipulation-resistant construction (median of an AMM + oracle feeds, quorum, depeg + deviation
///         bounds) is task 0081; it is implemented BEHIND this interface and swapped in without touching consumers.
interface IGreaterMarketReference {
    function greaterMarketPrice(uint256 collateralId)
        external
        view
        returns (uint256 priceUsd18, bool valid);
}

src/interfaces/IOracleAdapter.sol

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

/// @notice Machine-checkable provenance of an oracle adapter. The attested/market boundary MUST be a
///         typed value, not a name (a name implying a property it lacks is a CRITICAL finding).
enum OracleKind {
    Unset, // default / uninitialised — never valid for admission
    Mock, // test / demo only — MUST NOT pass production admission
    AttestedQuorum // multi-source (Pyth/Chainlink/RedStone) quorum + staleness/deviation/composite guards
}

/// @title IOracleAdapter — guarded valuation price for ONE (collateral, purpose)
/// @notice One adapter instance per (collateral, price purpose). A collateral's `CollateralRegistry`
///         entry references three purposes — mint/open/withdraw, slow-liquidation, fast-liquidation —
///         each pointing at its own adapter, so the *purpose* is the deployment, not a call argument.
///
///         PRODUCTION SHAPE (supersedes `TODO-ORACLE-001`; see docs/oracle-and-execution-pricing.md,
///         "Mandatory obligations"). A production adapter aggregates the gold-standard sources
///         (Pyth, Chainlink, RedStone), applies staleness + deviation bounds and an N-of-M quorum, and
///         for wstETH composes `ETH/USD × wstETH/ETH` where the wstETH/ETH leg IS the on-chain Lido NAV
///         (`stEthPerToken`) with a one-sided cap — a market pair is NEVER an input to eligibility.
///
///         This price answers ELIGIBILITY / valuation only ("what is it worth for CR / liquidation
///         eligibility"). It is NOT an executable sale price — for "what can we actually realize dumping
///         it", use `IExecutionQuote`. The two must never cross jobs; that boundary is enforced by
///         `oracleKind()` + registry admission, not by naming.
interface IOracleAdapter {
    /// @notice The guarded price, 1e18-scaled USD per whole collateral token. Reverts on any safety
    ///         failure (stale source, quorum not met, deviation breach). Never returns zero. This is the
    ///         ONLY method CR/eligibility consumers may use.
    function price() external view returns (uint256);

    /// @notice Provenance of this adapter. Registry admission for an eligibility slot MUST require
    ///         `AttestedQuorum`; `Mock`/`Unset` MUST be rejected on any value-bearing network.
    function oracleKind() external view returns (OracleKind);

    /// @notice Non-reverting guarded observation for monitoring / keepers / UI and terminal lot-loss
    ///         allocation (0336). Loss valuation must check validity and a nonzero price before use;
    ///         invalid observations defer loss, never value it at zero. FAIL-CLOSED: when `valid == false`,
    ///         `priceE18` MUST be 0, so a caller that
    ///         ignores `valid` cannot read a usable-looking stale number. CR/eligibility consumers MUST
    ///         still use `price()`, never `peek()`.
    function peek() external view returns (uint256 priceE18, bool valid);

    /// @notice Observability / audit metadata ONLY — MUST NOT drive any pricing decision. May be a
    ///         below-quorum or stale aggregate; when below quorum `priceE18` MUST be 0.
    /// @return priceE18 the aggregated price
    /// @return updatedAt the freshest source timestamp used
    /// @return sourcesUsed how many sources contributed to the aggregate
    /// @return sourcesRequired the quorum threshold that must be met
    function latest()
        external
        view
        returns (uint256 priceE18, uint256 updatedAt, uint8 sourcesUsed, uint8 sourcesRequired);

    /// @notice Human-readable descriptor (observability only; provenance is `oracleKind()`), e.g.
    ///         "wstETH/USD composite - 2-of-3 (Pyth,Chainlink,RedStone)".
    function description() external view returns (string memory);
}

src/interfaces/IPRUSD.sol

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

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

/// @notice PRUSD as consumed by the protocol: an ERC-20 with role-gated mint/burn.
interface IPRUSD is IERC20 {
    function mint(address to, uint256 amount) external;
    function burn(address from, uint256 amount) external;
}

src/interfaces/ISettlementExecutor.sol

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

/// @notice The collateral-sale executor a StabilityPool calls INSIDE `realize` (0045A ↔ 0059A seam). The pool
///         hands it `collateralAmount` of `collateralToken` and calls `executeSale` in the same atomic,
///         `nonReentrant` call; the executor must sell and deliver the PRUSD proceeds back to the caller (the
///         pool). The pool measures the realized proceeds as its own balance delta — it never trusts a returned
///         amount — so a failed or under-delivering sale rolls the whole realization back. 0059A implements this
///         over the V4 clip sale at the execution price (never the eligibility oracle).
interface ISettlementExecutor {
    function executeSale(address collateralToken, uint256 collateralAmount, bytes calldata data)
        external;
}

src/interfaces/ISettlementPool7540.sol

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

/// @notice Minimal registration and cycle identity for the ledger-only, self-share pool.
interface ISettlementPool7540 {
    function asset() external view returns (address);
    function share() external view returns (address);
    function collateralId() external view returns (uint256);
    function settlementLedger() external view returns (address);
    function settlementPending() external view returns (bool);
    function cycleId() external view returns (uint256);
    function absorbedDebt() external view returns (uint256);
    function tabReceivable() external view returns (uint256);
    function claimTab() external view returns (uint256);
    function earningsTab() external view returns (uint256);
}

interface ISettlementSourceRegistry {
    function settlementSource(address pool) external view returns (address);
}

/// @notice Treasury's governance-bound, set-once Vault identity.
interface ILiquidationVaultBinding {
    function vault() external view returns (address);
}

src/interfaces/IStabilityPoolRegistry.sol

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

import {PoolExposure, StabilityPoolInfo} from "../types/ProtocolTypes.sol";
import {IPRUSD} from "./IPRUSD.sol";

/// @notice Stability pool metadata + collateral watching. A collateralId is watched by at most one
///         active pool; a facility routes liquidations to exactly one pool. Pools do not compete.
interface IStabilityPoolRegistry {
    event PoolRegistered(
        uint256 indexed poolId,
        address indexed pool,
        address indexed shareToken,
        PoolExposure exposure
    );
    event CollateralWatched(uint256 indexed poolId, uint256 indexed collateralId);
    event PoolActiveSet(uint256 indexed poolId, bool active);

    /// @notice The canonical debt token every pool burns and every facility must commit to.
    function prusd() external view returns (IPRUSD);

    function getPool(uint256 poolId) external view returns (StabilityPoolInfo memory);

    /// @notice The registered identity of `pool`, regardless of whether liquidation routing is active.
    function poolIdForPool(address pool) external view returns (uint256 poolId);

    /// @notice The single active pool watching `collateralId`, or 0 if none.
    function poolForCollateral(uint256 collateralId) external view returns (uint256 poolId);
}

src/interfaces/IStabilityPoolSettlementLedger.sol

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

/// @notice Integration boundary for the warehouse Treasury's non-transferable receivable ledger.
/// @dev Implementations must authenticate completed warehouse operations, bind their proceeds to
///      (msg.sender pool, cycleId, absorbedDebt), and reject incomplete or consumed cycles.
///      consumeSettlement returns gross cash/TAB evidence, but transfers cash and creates TAB net
///      of SettlementProfit.cuts(absorbedDebt, cash, tab). The pool validates gross evidence before
///      accepting those net amounts. The operational settlement key cannot author these records.
interface IStabilityPoolSettlementLedger {
    function consumeSettlement(uint256 cycleId, uint256 absorbedDebt)
        external
        returns (uint256 grossCash, uint256 grossTab);

    function outstanding(address pool) external view returns (uint256);

    /// @dev Receives final-exit cash fees and extinguishes the pool's corresponding TAB fee claim.
    function receiveFinalExitPenalty(uint256 cash, uint256 tab) external;
}

src/interfaces/ITreasury.sol

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

/// @notice Protocol backstop / realised-sale accounting / emergency liquidity / PSM mint path.
/// @dev Standalone by design — Treasury logic must never be folded into Vault or StabilityPool.
///      The full backstop surface (backstopBuy/backstopBorrow, PSM mint, ledger TAB issue/retire, arb) lands
///      in a later task; this interface fixes the integration seam and events for the subgraph.
import {IPRUSD} from "./IPRUSD.sol";

interface ITreasury {
    /// @notice The canonical PRUSD the Treasury accounts in — a StabilityPool validates its bound Treasury shares
    ///         the pool's PRUSD before routing the liquidation-profit split to it (0045A).
    function prusd() external view returns (IPRUSD);

    event BackstopBuyExecuted(
        uint256 indexed poolId, uint256 collateralAmount, uint256 prusdMinted
    );
    event BackstopBorrowExecuted(address indexed borrower, uint256 indexed facilityId);
    event InterestCollected(uint256 indexed facilityId, uint256 amount);
    event LiquidationPremiumTaken(uint256 indexed poolId, uint256 amount);

    /// @notice Per-pool backstop ledger (0067) — attribution only. Aggregation key is `poolId`; `collateralId`
    ///         is metadata. Emitted on every ledger movement for the risk dashboard/subgraph.
    event BackstopAdvanceRecorded(
        uint256 indexed poolId,
        uint256 indexed collateralId,
        uint256 prusdAdvanced,
        uint256 iouIssued,
        uint256 collateralReceivedValue,
        uint256 unresolvedExposureAfter,
        uint256 at
    );
    event BackstopResolutionRecorded(
        uint256 indexed poolId,
        uint256 indexed collateralId,
        uint256 collateralSoldValue,
        uint256 reserveRecovered,
        int256 realizedPnL,
        uint256 unresolvedExposureAfter,
        uint256 at
    );

    /// @notice Revenue attribution seam (0058), called by the Vault + StabilityPool holding REVENUE_SOURCE_ROLE.
    ///         The two-phase checkpoint binds fee/interest attribution to a MEASURED balance delta; only ONE may
    ///         be open at a time (the caller must run begin→transfer→finalize in ONE transaction).
    function beginRecord(bytes32 operationId) external;
    function finalizeRecord(bytes32 operationId, bytes32 source, uint256 expectedAmount) external;
}

src/interfaces/IWarehouseCycleSource.sol

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

/// @notice Atomic warehouse capability, distinct from intake-only custody.
interface IWarehouseCycleSource {
    function pool() external view returns (address);
    function vault() external view returns (address);
    function treasury() external view returns (address);
    function registry() external view returns (address);
    function collateralId() external view returns (uint256);
    function poolId() external view returns (uint256);
    function isCycleReady() external view returns (bool);
    function cycle(uint256 maximum, bytes calldata data) external;
}

src/interfaces/IWarehouseRegistry.sol

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

interface IWarehouseRegistry {
    event WarehouseCreated(
        uint256 indexed collateralId,
        uint256 indexed poolId,
        address indexed warehouse,
        address collateralToken,
        uint8 collateralDecimals,
        address pool,
        address vault,
        address treasury
    );

    function createWarehouse(uint256 collateralId, uint256 poolId) external returns (address);
    function warehouseForCollateral(uint256 collateralId) external view returns (address);
}

src/libraries/RevenueSources.sol

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

/// @notice Canonical revenue-source tags for Treasury attribution (0058). Single source of truth so the Vault,
///         the StabilityPool, and the Treasury agree on the bucket a checkpoint attributes to — a mismatched
///         inline `keccak256` would silently misclassify revenue.
library RevenueSources {
    bytes32 internal constant FEE = keccak256("FEE");
    bytes32 internal constant INTEREST = keccak256("INTEREST");
    bytes32 internal constant LIQ_PROFIT = keccak256("LIQ_PROFIT");
    bytes32 internal constant EARLY_EXIT_PENALTY = keccak256("EARLY_EXIT_PENALTY");
    bytes32 internal constant ARBITRAGE = keccak256("ARBITRAGE"); // task 0201: waterfall step 1 profit
    bytes32 internal constant DONATION = keccak256("DONATION"); // task 0290: gifts sold or booked
}

src/libraries/Roles.sol

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

/// @notice Canonical access-control role identifiers.
/// @dev Every privileged surface maps to a role here and to a row in
///      docs/security/wallet-register.md. All roles are assignable to a multisig/timelock — no EOA
///      assumptions, no `tx.origin`. `DEFAULT_ADMIN_ROLE` (0x00) comes from OZ AccessControl.
library Roles {
    /// @notice Registry/protocol wiring (bindings, pool registration).
    bytes32 internal constant REGISTRY_ADMIN_ROLE = keccak256("REGISTRY_ADMIN_ROLE");
    /// @notice Risk parameters + collateral/facility admission (economically mint-grade).
    bytes32 internal constant RISK_ADMIN_ROLE = keccak256("RISK_ADMIN_ROLE");
    /// @notice Publishes/deprecates typed oracle route definitions in the on-chain `FeedCatalogue` (task 0081 U3).
    ///         DATA admission for the pricing surface — it controls which feeds a price profile may be built from; it
    ///         moves no value and mints nothing, but a bad definition mis-prices `G`. Separation from `EMERGENCY_ROLE`
    ///         is ENFORCED on-chain by the catalogue's role-commingling guard; the custody posture (multisig/timelock)
    ///         is ratified with its `docs/security/wallet-register.md` row at deployment (task 0081 U10–U12).
    bytes32 internal constant FEED_PUBLISHER_ROLE = keccak256("FEED_PUBLISHER_ROLE");
    /// @notice Pause/halt of value-moving contracts. Held separately from the registry admin.
    bytes32 internal constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE");
    /// @notice Liquidation authority. Single ACTIVE holder per pool (race avoidance); rotatable.
    bytes32 internal constant LIQUIDATOR_ROLE = keccak256("LIQUIDATOR_ROLE");
    /// @notice Sepolia/local-only whole-debt seizure for testing. Never grant to a keeper lane.
    bytes32 internal constant TEST_LIQUIDATOR_ROLE = keccak256("TEST_LIQUIDATOR_ROLE");
    /// @notice Test-deployment teardown (task 0300): `drain(token, amount)` on the Treasury, vault, pools,
    ///         warehouses, stable reserves and CoW sellers. Granted by the deploy script only when `DRAIN_ADDRESS`
    ///         is set; held on the Treasury, vault and pool. Pre-audit removal list.
    bytes32 internal constant TEST_DRAIN_ROLE = keccak256("TEST_DRAIN_ROLE");
    /// @notice Task 0301: the interest offset contract, the only caller that may set the PRYA assigned to a loan in
    ///         the facility registry. Held by that contract alone, never a wallet.
    bytes32 internal constant OFFSET_ROLE = keccak256("OFFSET_ROLE");
    /// @notice Task 0302: the keeper's buyback lane wallet, the only caller that may open a buyback round or buy a tranche
    ///         on `PryaBuyback`. Its own wallet, never shared with another lane.
    bytes32 internal constant BUYBACK_ROLE = keccak256("BUYBACK_ROLE");
    /// @notice PRUSD mint authority (vault debt path + treasury PSM path).
    bytes32 internal constant MINTER_ROLE = keccak256("MINTER_ROLE");
    /// @notice PRUSD burn authority (repay / window burn).
    bytes32 internal constant BURNER_ROLE = keccak256("BURNER_ROLE");
    /// @notice Treasury operations (backstop / PSM / realised-sale accounting).
    bytes32 internal constant TREASURY_ROLE = keccak256("TREASURY_ROLE");
    /// @notice The vault, authorised to update facility debt accounting and drive pool absorption.
    bytes32 internal constant VAULT_ROLE = keccak256("VAULT_ROLE");
    /// @notice Local warehouse draft only: pool-side funding permission for the canonical warehouse
    ///         contract, independently granted from the Treasury's settlement-source binding. Never an EOA.
    bytes32 internal constant WAREHOUSE_FUNDING_ROLE = keccak256("WAREHOUSE_FUNDING_ROLE");
    /// @notice Revenue sources authorised to record Treasury inflows (Vault fee/interest, StabilityPool
    ///         liquidation profit). Attribution is a privileged surface — only protocol contracts hold it.
    bytes32 internal constant REVENUE_SOURCE_ROLE = keccak256("REVENUE_SOURCE_ROLE");
    /// @notice Stability-Pool share issuance — mint/burn of per-pool wPRUSD share tokens. Held by the pool,
    ///         NOT the Vault (the pool issues shares against deposits; the vault never touches share supply).
    bytes32 internal constant SHARE_ISSUER_ROLE = keccak256("SHARE_ISSUER_ROLE");
    /// @notice Collateral-realization authority (0045A): calls `StabilityPool.realize` to sell pending settlement
    ///         collateral. The 0059A keeper holds it; distinct from LIQUIDATOR_ROLE + the loss-accept EMERGENCY_ROLE.
    bytes32 internal constant SETTLEMENT_ROLE = keccak256("SETTLEMENT_ROLE");
    /// @notice Greater-market FLOOR realization authority (0080 D1): calls `StabilityPool.realizeAtFloor` — the
    ///         routine floor-limited path that MAY realize below cost + trigger a Treasury buyer-of-last-resort mint.
    ///         DELIBERATELY SEPARATE from `SETTLEMENT_ROLE` (its own dedicated keeper wallet) so this narrower, more
    ///         consequential authority never rides the plain settlement key; NEVER the loss-accept `EMERGENCY_ROLE`.
    bytes32 internal constant FLOOR_SETTLEMENT_ROLE = keccak256("FLOOR_SETTLEMENT_ROLE");
    /// @notice The backstop path, authorised to WRITE the Treasury's per-pool backstop ledger (0067).
    ///         ATTRIBUTION ONLY — does not move funds or mint. Kept strictly separate from the fund-moving
    ///         `BACKSTOP_ASSUME_ROLE` so granting a keeper ledger-write access can never grant vault seizure.
    bytes32 internal constant BACKSTOP_ROLE = keccak256("BACKSTOP_ROLE");
    /// @notice FUND-MOVING: authorises `Vault.assumeVault` — seizing a whole unfundable vault's collateral +
    ///         burning to clear its principal (0068). Held ONLY by the wired Treasury. Distinct from
    ///         `BACKSTOP_ROLE` (attribution) so the two capabilities are never conflated.
    bytes32 internal constant BACKSTOP_ASSUME_ROLE = keccak256("BACKSTOP_ASSUME_ROLE");

    // ── 0069 role split — narrow lanes carved out of the former coarse `TREASURY_ROLE` so one leaked keeper key
    //    can't do everything. Each is granted to its OWN wallet (task 0069 / scenario §5.7).
    /// @notice Routine floor-protected hotswap clip — `Treasury.backstopResolve` (hot keeper). Floor-gated on-chain.
    bytes32 internal constant HOTSWAP_ROLE = keccak256("HOTSWAP_ROLE");
    /// @notice Backstop vault-assumption TRIGGER — `Treasury.backstopAssumeVault` (guarded keeper/operator; on-chain
    ///         guarded to only liquidatable+unfundable vaults). DISTINCT from the contract-held `BACKSTOP_ASSUME_ROLE`
    ///         (the Treasury's permission ON the Vault), which no wallet ever holds.
    bytes32 internal constant BACKSTOP_OPERATOR_ROLE = keccak256("BACKSTOP_OPERATOR_ROLE");
    /// @notice Legacy reference-contract role for Treasury.repayIou. No current production
    ///         entrypoint accepts this role; old TAB repayment is waterfall-only.
    bytes32 internal constant TREASURY_REPAY_ROLE = keccak256("TREASURY_REPAY_ROLE");

    /// @notice Triggers `TreasuryWaterfall.run` (task 0197). May only say "run" over a list of pools and reserves;
    ///         every amount is computed on-chain from live figures. Granted on the waterfall contract to the keeper's
    ///         waterfall wallet, never folded into a broad Treasury role.
    bytes32 internal constant WATERFALL_ROLE = keccak256("WATERFALL_ROLE");

    // IOU_CREDIT_ROLE removed (0079 slice 2): the slice-1 `StabilityPool.creditIou` seam is gone — TAB is credited
    // ONLY via the atomic balance-delta inside `_realizeCore`, so no external credit role exists.
}

src/libraries/SalePricing.sol

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

interface ISalePricingEvents {
    event SalePricing(
        address indexed executor,
        address collateral,
        address output,
        uint256 oracleUsd18,
        uint256 outputUsd18,
        uint256 slippageBps,
        uint256 coverage18,
        uint256 floor,
        uint256 offered
    );
    event SaleMeasured(address indexed executor, uint256 sold, uint256 received);
}

/// @dev Reporting only. Values come from the valuation that set the floor, never another oracle read.
library PricingEvidence {
    struct Quote {
        uint256 oracleUsd18;
        uint256 outputUsd18;
        uint256 slippageBps;
        uint256 coverage18;
    }

    function record(
        address executor,
        address collateral,
        address output,
        uint256 floor,
        uint256 offered,
        Quote memory q
    ) internal {
        emit ISalePricingEvents.SalePricing(
            executor,
            collateral,
            output,
            q.oracleUsd18,
            q.outputUsd18,
            q.slippageBps,
            q.coverage18,
            floor,
            offered
        );
    }
}

src/libraries/SettlementProfit.sol

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

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

/// @dev Legacy StabilityPool._closeSettlement economics, shared by the cash sender and receiver.
library SettlementProfit {
    function cuts(uint256 cost, uint256 cash, uint256 tab)
        internal
        pure
        returns (uint256 cashCut, uint256 tabCut)
    {
        uint256 proceeds = cash + tab;
        if (proceeds <= cost) return (0, 0);
        uint256 cut = (proceeds - cost) / 5; // Exactly floor(profit * 2000 / 10_000), without a product.
        cashCut = Math.min(cut, cash > cost ? cash - cost : 0);
        tabCut = cut - cashCut;
    }
}

src/libraries/SrvLossMath.sol

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

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

/// @notice Allocate additional debt, never subtract backing. Work is bounded by reserve count, not loss size.
library SrvLossMath {
    error InvalidSnapshot();

    function allocate(
        uint256[] memory value,
        uint256[] memory debt,
        address[] memory assets,
        uint256 loss
    ) internal pure returns (uint256[] memory allocation, uint256 retained) {
        uint256 n = value.length;
        if (debt.length != n || assets.length != n) revert InvalidSnapshot();
        allocation = new uint256[](n);
        uint256[] memory current = new uint256[](n);
        for (uint256 j; j < n; ++j) {
            current[j] = debt[j];
        }
        retained = loss;
        uint256[4] memory cliffs = [uint256(10_000), 9800, 9500, 9000];
        for (uint256 t; t < 4 && retained != 0; ++t) {
            uint256[] memory capacity = new uint256[](n);
            uint256[] memory fractions = new uint256[](n);
            for (uint256 j; j < n; ++j) {
                uint256 ceiling = Math.mulDiv(value[j], 10_000, cliffs[t]);
                if (ceiling > current[j]) {
                    capacity[j] = ceiling - current[j];
                    fractions[j] = mulmod(value[j], 10_000, cliffs[t]);
                }
            }
            (uint256[] memory step, uint256 left) = level(capacity, fractions, assets, retained);
            retained = left;
            for (uint256 j; j < n; ++j) {
                current[j] += step[j];
                allocation[j] += step[j];
            }
        }
        if (retained == 0) return (allocation, 0);
        uint256 total;
        for (uint256 j; j < n; ++j) {
            total += current[j];
        }
        if (total == 0) return (allocation, retained);
        uint256 distributed;
        uint256[] memory remainders = new uint256[](n);
        bool[] memory eligible = new bool[](n);
        for (uint256 j; j < n; ++j) {
            uint256 part = Math.mulDiv(retained, current[j], total);
            allocation[j] += part;
            distributed += part;
            remainders[j] = mulmod(retained, current[j], total);
            eligible[j] = current[j] != 0;
        }
        // Largest remainders allocate at most one extra wei per receiver; addresses break exact ties only.
        distributeRemainder(allocation, remainders, assets, eligible, retained - distributed);
        return (allocation, 0);
    }

    function level(
        uint256[] memory cap,
        uint256[] memory fractions,
        address[] memory assets,
        uint256 budget
    ) private pure returns (uint256[] memory out, uint256 left) {
        uint256 n = cap.length;
        out = new uint256[](n);
        uint256[] memory order = new uint256[](n);
        for (uint256 j; j < n; ++j) {
            order[j] = j;
            uint256 k = j;
            while (k != 0 && cap[order[k]] > cap[order[k - 1]]) {
                (order[k], order[k - 1]) = (order[k - 1], order[k]);
                --k;
            }
        }
        left = budget;
        for (uint256 count = 1; count <= n && left != 0; ++count) {
            uint256 next = count == n ? 0 : cap[order[count]];
            uint256 drop = cap[order[count - 1]] - next;
            if (drop > left / count) {
                uint256 each = left / count;
                bool[] memory eligible = new bool[](n);
                for (uint256 j; j < count; ++j) {
                    out[order[j]] += each;
                    eligible[order[j]] = true;
                }
                distributeRemainder(out, fractions, assets, eligible, left % count);
                return (out, 0);
            }
            for (uint256 j; j < count; ++j) {
                out[order[j]] += drop;
            }
            left -= drop * count;
        }
    }

    function distributeRemainder(
        uint256[] memory out,
        uint256[] memory fractions,
        address[] memory assets,
        bool[] memory eligible,
        uint256 remainder
    ) private pure {
        for (uint256 r; r < remainder; ++r) {
            uint256 best = type(uint256).max;
            for (uint256 j; j < out.length; ++j) {
                if (
                    eligible[j]
                        && (best == type(uint256).max
                            || fractions[j] > fractions[best]
                            || (fractions[j] == fractions[best]
                                && uint160(assets[j]) < uint160(assets[best])))
                ) best = j;
            }
            if (best == type(uint256).max) revert InvalidSnapshot();
            out[best]++;
            eligible[best] = false;
        }
    }
}

src/libraries/StableReserveMath.sol

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

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

/// @notice Unit conversion and warehouse-v2 SRV payout arithmetic; no issuance or loss-allocation policy.
library StableReserveMath {
    error UnsupportedDecimals();
    error NormalizationOverflow();
    error DebtExceeded();
    error InvalidFee();

    function normalize(uint256 backingUnits, uint8 decimals) internal pure returns (uint256) {
        uint256 scale = _scale(decimals);
        if (backingUnits > type(uint256).max / scale) revert NormalizationOverflow();
        return backingUnits * scale;
    }

    /// @dev Gross/net use external-token units; debt/amount/fee use PRUSD's 18 decimals.
    ///      min(amount / scale, amount * backing / debt) avoids normalizing the entire backing
    ///      balance or truncating B/D before multiplication. The caller must validate zero output,
    ///      custody, authorization, fee policy and slippage before executing any burn or transfer.
    function quoteRedemption(
        uint256 backingUnits,
        uint256 debt,
        uint256 amount,
        uint8 decimals,
        uint256 feeBps
    ) internal pure returns (uint256 gross, uint256 net, uint256 fee) {
        uint256 scale = _scale(decimals);
        if (amount > debt) revert DebtExceeded();
        if (feeBps > 10_000) revert InvalidFee();
        if (amount == 0) return (0, 0, 0);
        gross = Math.min(amount / scale, Math.mulDiv(amount, backingUnits, debt));
        fee = Math.mulDiv(amount, feeBps, 10_000, Math.Rounding.Ceil);
        uint256 burned = amount - fee;
        net = Math.min(burned / scale, Math.mulDiv(burned, backingUnits, debt));
    }

    function _scale(uint8 decimals) private pure returns (uint256) {
        if (decimals > 18) revert UnsupportedDecimals();
        return 10 ** (18 - decimals);
    }
}

src/libraries/SupportedChains.sol

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

/// @notice The chains the warehouse system deploys and runs on: Ethereum mainnet, Sepolia and the local Anvil chain.
///         One list for every core contract (Bevan, 22 Oct 2026: "allow mainnet, sepolia and anvil"). The test fakes in
///         `src/testing/` keep their own testnet-only gate and must never deploy on mainnet.
library SupportedChains {
    error UnsupportedChain(uint256 chainId);

    uint256 internal constant MAINNET = 1;
    uint256 internal constant SEPOLIA = 11_155_111;
    uint256 internal constant ANVIL = 31_337;

    error TestnetOnly(uint256 chainId);

    function check() internal view {
        uint256 id = block.chainid;
        if (id != MAINNET && id != SEPOLIA && id != ANVIL) revert UnsupportedChain(id);
    }

    /// @notice Testnet-only tools retain this gate. The role-controlled forced seizure in the mainnet test
    ///         build (task 0310) is separate; fake mainnet prices remain forbidden.
    function checkTestnet() internal view {
        uint256 id = block.chainid;
        if (id != SEPOLIA && id != ANVIL) revert TestnetOnly(id);
    }
}

src/libraries/TestDrain.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {Roles} from "./Roles.sol";

/// @notice Task 0300: test-deployment teardown. A `TEST_DRAIN_ROLE` holder takes any token out of a protocol
///         contract with no accounting update; the deployment's books are meaningless afterwards. No contract
///         grants the role itself: the deploy script grants it only when `DRAIN_ADDRESS` is set. On the
///         pre-audit removal list.
library TestDrain {
    using SafeERC20 for IERC20;

    event Drained(address indexed token, uint256 amount, address indexed to);

    error NotDrainer(address caller);

    /// @dev For contracts without a role table of their own: the Treasury's role table decides.
    function requireTreasuryRole(address treasury) internal view {
        if (!IAccessControl(treasury).hasRole(Roles.TEST_DRAIN_ROLE, msg.sender)) {
            revert NotDrainer(msg.sender);
        }
    }

    /// @dev Sends to the caller, the role holder, so a drain cannot be pointed at another wallet.
    function send(address token, uint256 amount) internal {
        IERC20(token).safeTransfer(msg.sender, amount);
        emit Drained(token, amount, msg.sender);
    }
}

src/libraries/TreasuryCow.sol

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

import {Lot} from "../types/LotTypes.sol";
import {TreasuryFold} from "./TreasuryFold.sol";
import {TreasurySales} from "./TreasurySales.sol";
import {RevenueSources} from "./RevenueSources.sol";
import {StableReserveRegistry} from "../registries/StableReserveRegistry.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {ISettlementPool7540} from "../interfaces/ISettlementPool7540.sol";
import {IStabilityPoolRegistry} from "../interfaces/IStabilityPoolRegistry.sol";
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";

/// @dev Narrow custody interface keeps CoW's compiler profile outside Treasury.
interface IPartialCowSeller {
    function treasury() external view returns (address);
    function owner() external view returns (address);
    function registry() external view returns (address);
    function collateralId() external view returns (uint256);
    function sellToken() external view returns (IERC20);
    function buyToken() external view returns (IERC20);
    function totalDebited() external view returns (uint256);
    function totalFunded() external view returns (uint256);
    function totalCollected() external view returns (uint256);
    function fund(uint256 amount) external;
    function collect() external returns (uint256);
    function returnCollateral() external returns (uint256);
}

interface IPartialCowAccounting {
    function bookCowCompletion(
        TreasuryCow.Completion calldata completion,
        address asset,
        address reserve
    ) external;
    function vault() external view returns (address);
    function prusd() external view returns (address);
    function reserveRegistry() external view returns (address);
    function inventoryPoolId(uint256 cid) external view returns (uint256);
    function poolRegistry() external view returns (IStabilityPoolRegistry);
    function seizedInventory(uint256 cid) external view returns (uint256);
}

interface ICowLotEvents {
    event CowSellerFunded(address indexed seller, bytes32 indexed lotId, uint256 amount);
    event CowSellerAllocated(
        address indexed seller, bytes32 indexed lotId, uint256 sold, uint256 received
    );
    event CowSellerReturned(address indexed seller, bytes32 indexed lotId, uint256 returned);
    event CowSellerUnclassified(address indexed seller, address indexed token, uint256 amount);
    event CowCycleSellerFunded(
        address indexed seller, uint256 indexed poolId, uint256 indexed cycle, uint256 amount
    );
    event CowDonationAdmitted(address indexed seller, uint256 indexed collateralId, uint256 amount);
    event CowUnclassifiedBooked(address indexed seller, address indexed token, uint256 amount);
}

/// @dev Linked order custody ledger; completed fills use the existing fold accounting.
library TreasuryCow {
    using SafeERC20 for IERC20;
    error InvalidLotReservation();
    error LotCollateralReserved(bytes32 lotId, uint256 requested, uint256 available);
    error LotSettlementPending(bytes32 lotId);
    error CustodyMismatch();

    struct Completion {
        uint256 poolId;
        uint256 collateralId;
        uint256 sold;
        uint256 received;
        uint256 interest;
        uint256 surplus;
        uint256 cycle;
        /// @dev The revenue source of a completion with no pool (a donation, 0290); zero otherwise.
        bytes32 source;
    }

    struct Ledger {
        mapping(bytes32 => uint256) reserved;
        mapping(uint256 => uint256) externalCollateral;
        mapping(address => SellerBook) sellers;
        mapping(address => uint256) unclassified;
        mapping(uint256 => address) sellerForCollateral;
        mapping(bytes32 => CycleSource) cycleSources;
        mapping(bytes32 => uint256) reservedCycle;
        mapping(uint256 => uint256) externalCycle;
        mapping(bytes32 => bool) donation;
        mapping(uint256 => uint256) idleDonation;
    }

    struct CycleSource {
        uint256 poolId;
        uint256 collateralId;
        uint256 cycle;
    }

    struct SellerBook {
        address reserve;
        uint256 remaining;
        uint256 debited;
        bytes32[] ids;
        mapping(bytes32 => uint256) contribution;
        uint256 epochWeight;
        uint256 epochSold;
        uint256 epochReceived;
        uint256 pendingSold;
        uint256 pendingReceived;
        mapping(bytes32 => uint256) weight;
        mapping(bytes32 => uint256) allocatedSold;
        mapping(bytes32 => uint256) allocatedReceived;
    }

    struct SettlementContext {
        address vault;
        address prusd;
        address registry;
    }

    enum ActionKind {
        Collect,
        FundLot,
        FundCycle,
        Return,
        Checkpoint,
        Sweep,
        BookUnclassified
    }

    struct Action {
        ActionKind kind;
        address seller;
        bytes32 lotId;
        uint256 cycle;
        uint256 amount;
    }

    function partialAction(
        Ledger storage self,
        mapping(bytes32 => Lot) storage lots,
        mapping(uint256 => uint256) storage collateral,
        TreasurySales.FoldLedger storage folds,
        TreasurySales.CycleLedger storage cycles,
        Action memory action
    ) external returns (uint256 lossInterest) {
        IPartialCowAccounting t = IPartialCowAccounting(address(this));
        SettlementContext memory ctx = SettlementContext(t.vault(), t.prusd(), t.reserveRegistry());
        lossInterest = settlePartial(
            self, lots, collateral, folds, action.seller, ctx, action.kind != ActionKind.Collect
        );
        if (action.kind == ActionKind.FundLot) {
            fundPartial(self, lots, ctx.registry, action.seller, action.lotId, action.amount);
        } else if (action.kind == ActionKind.FundCycle) {
            uint256 cid = IPartialCowSeller(action.seller).collateralId();
            uint256 pid = t.inventoryPoolId(cid);
            if (
                pid == 0
                    || ISettlementPool7540(t.poolRegistry().getPool(pid).pool).settlementPending()
            ) {
                revert InvalidLotReservation();
            }
            fundCycle(
                self, cycles, ctx.registry, action.seller, pid, cid, action.cycle, action.amount
            );
        } else if (action.kind == ActionKind.Return) {
            returnPartial(self, lots, action.seller);
        } else if (action.kind == ActionKind.Sweep) {
            sweep(self, collateral, ctx.registry, action.seller, action.amount);
        } else if (action.kind == ActionKind.BookUnclassified) {
            bookUnclassified(self, ctx, action.seller);
        }
    }

    /// @notice Task 0290 (scenario D01 to D05, D11): collateral this Treasury holds that no lot, cycle or returned
    ///         donation explains is a gift. It is admitted all at once as the seller's donation contribution (no
    ///         debt, no cycle) and funded with any returned donation. Runs after the fills above are booked, so a
    ///         gift never shares in an earlier fill. Less held than explained is a custody error, never a negative
    ///         gift. A gift below `minimum` (threshold H) is left unadmitted.
    function sweep(
        Ledger storage self,
        mapping(uint256 => uint256) storage collateral,
        address registry,
        address owner,
        uint256 minimum
    ) private {
        IPartialCowSeller seller = IPartialCowSeller(owner);
        uint256 cid = seller.collateralId();
        bindSeller(self, registry, owner, cid);
        IERC20 token = seller.sellToken();
        // At sellers: externalCollateral of lot collateral and externalCycle of seized inventory.
        uint256 explained = IPartialCowAccounting(address(this)).seizedInventory(cid)
            + collateral[cid] + self.idleDonation[cid] - self.externalCollateral[cid]
            - self.externalCycle[cid];
        uint256 held = token.balanceOf(address(this));
        if (held < explained) revert CustodyMismatch();
        uint256 gift = held - explained;
        if (gift < minimum) gift = 0;
        uint256 amount = gift + self.idleDonation[cid];
        if (amount == 0) return;
        if (gift != 0) {
            // Unclassified collateral returned by a seller is part of the gift and is admitted with it, once.
            delete self.unclassified[address(token)];
            emit ICowLotEvents.CowDonationAdmitted(owner, cid, gift);
        }
        delete self.idleDonation[cid];
        bytes32 id = keccak256(abi.encode("cow-donation", cid));
        self.donation[id] = true;
        fundContribution(self.sellers[owner], owner, id, amount);
    }

    /// @notice Task 0290 (scenario D06): USDC that reached a seller with no sale is donation income. All of the
    ///         bucket is deposited into the seller's reserve and minted to this Treasury as `DONATION` revenue.
    function bookUnclassified(Ledger storage self, SettlementContext memory ctx, address owner)
        private
    {
        // A Treasury control, signed by the Treasury admin alone: the Treasury's entry skips its hotswap check for
        // this kind. A delegate call keeps the Treasury's caller, so this checks the signer of the Treasury call.
        if (!IAccessControl(address(this)).hasRole(0, msg.sender)) {
            revert IAccessControl.AccessControlUnauthorizedAccount(msg.sender, 0);
        }
        IPartialCowSeller seller = IPartialCowSeller(owner);
        uint256 cid = seller.collateralId();
        bindSeller(self, ctx.registry, owner, cid);
        address asset = address(seller.buyToken());
        uint256 amount = self.unclassified[asset];
        if (amount == 0) return;
        delete self.unclassified[asset];
        address reserve = self.sellers[owner].reserve;
        Completion memory c;
        c.collateralId = cid;
        c.received = amount;
        c.source = RevenueSources.DONATION;
        c.surplus = TreasuryFold.depositBacking(ctx.registry, ctx.prusd, asset, reserve, amount, 0);
        IPartialCowAccounting(address(this)).bookCowCompletion(c, asset, reserve);
        emit ICowLotEvents.CowUnclassifiedBooked(owner, asset, amount);
    }

    function fundPartial(
        Ledger storage self,
        mapping(bytes32 => Lot) storage lots,
        address registry,
        address owner,
        bytes32 id,
        uint256 amount
    ) private {
        Lot storage lot = lots[id];
        if (amount == 0 || lot.poolId == 0) revert InvalidLotReservation();
        bindSeller(self, registry, owner, lot.collateralId);
        SellerBook storage book = self.sellers[owner];
        checkAvailable(self, id, lot.collateral, amount);
        self.reserved[id] += amount;
        self.externalCollateral[lot.collateralId] += amount;
        fundContribution(book, owner, id, amount);
        emit ICowLotEvents.CowSellerFunded(owner, id, amount);
    }

    function configureSeller(Ledger storage self, address registry, address owner, uint256 cid)
        external
    {
        bindSeller(self, registry, owner, cid);
    }

    function bindSeller(Ledger storage self, address registry, address owner, uint256 cid) private {
        IPartialCowSeller seller = IPartialCowSeller(owner);
        if (
            seller.treasury() != address(this) || seller.owner() != address(this)
                || seller.registry() != registry || seller.collateralId() != cid
        ) {
            revert InvalidLotReservation();
        }
        address configured = self.sellerForCollateral[cid];
        if (configured != address(0) && configured != owner) revert InvalidLotReservation();
        (address token,,) =
            StableReserveRegistry(registry).validateLotRoute(cid, address(seller.buyToken()), owner);
        if (token != address(seller.sellToken())) revert InvalidLotReservation();
        address backing =
            StableReserveRegistry(registry).validateDeposit(address(seller.buyToken()));
        SellerBook storage book = self.sellers[owner];
        if (book.reserve == address(0)) {
            if (
                seller.totalFunded() != 0 || seller.totalDebited() != 0
                    || seller.totalCollected() != 0
            ) {
                revert CustodyMismatch();
            }
            book.reserve = backing;
        }
        if (book.reserve != backing || book.debited != seller.totalDebited()) {
            revert CustodyMismatch();
        }
        self.sellerForCollateral[cid] = owner;
    }

    function fundCycle(
        Ledger storage self,
        TreasurySales.CycleLedger storage cycles,
        address registry,
        address owner,
        uint256 pid,
        uint256 cid,
        uint256 cycle,
        uint256 amount
    ) private {
        if (pid == 0 || cycle == 0 || amount == 0) revert InvalidLotReservation();
        bindSeller(self, registry, owner, cid);
        bytes32 id = keccak256(abi.encode("cow-cycle", pid, cycle));
        if (amount > cycles.collateral[pid][cycle] - self.reservedCycle[id]) {
            revert InvalidLotReservation();
        }
        self.cycleSources[id] = CycleSource(pid, cid, cycle);
        self.reservedCycle[id] += amount;
        self.externalCycle[cid] += amount;
        fundContribution(self.sellers[owner], owner, id, amount);
        emit ICowLotEvents.CowCycleSellerFunded(owner, pid, cycle, amount);
    }

    function fundContribution(SellerBook storage book, address owner, bytes32 id, uint256 amount)
        private
    {
        IPartialCowSeller seller = IPartialCowSeller(owner);
        IERC20 token = seller.sellToken();
        if (book.contribution[id] == 0) book.ids.push(id);
        book.contribution[id] += amount;
        book.remaining += amount;
        resetEpoch(book);
        uint256 balance = token.balanceOf(address(this));
        token.forceApprove(owner, amount);
        seller.fund(amount);
        token.forceApprove(owner, 0);
        if (token.balanceOf(address(this)) != balance - amount) revert CustodyMismatch();
    }

    function settlePartial(
        Ledger storage self,
        mapping(bytes32 => Lot) storage lots,
        mapping(uint256 => uint256) storage collateral,
        TreasurySales.FoldLedger storage folds,
        address owner,
        SettlementContext memory ctx,
        bool flushEpoch
    ) private returns (uint256 lossInterest) {
        SellerBook storage book = self.sellers[owner];
        if (book.reserve == address(0)) return 0;
        IPartialCowSeller seller = IPartialCowSeller(owner);
        uint256 debited = seller.totalDebited();
        uint256 sold = debited - book.debited;
        if (sold > book.remaining - book.pendingSold) revert CustodyMismatch();
        IERC20 asset = seller.buyToken();
        uint256 beforeBalance = asset.balanceOf(address(this));
        uint256 received = seller.collect();
        if (asset.balanceOf(address(this)) != beforeBalance + received) revert CustodyMismatch();
        if (sold == 0) {
            if (received != 0) {
                self.unclassified[address(asset)] += received;
                emit ICowLotEvents.CowSellerUnclassified(owner, address(asset), received);
            }
            if (!flushEpoch) return 0;
        } else {
            if (received == 0) revert CustodyMismatch();
            book.epochSold += sold;
            book.epochReceived += received;
            book.pendingSold += sold;
            book.pendingReceived += received;
        }
        book.debited = debited;
        if (book.epochWeight == 0) return 0;
        flushEpoch = flushEpoch || book.epochSold == book.epochWeight;
        uint256 prefix;
        uint256 previousSold;
        uint256 previousReceived;
        for (uint256 k; k < book.ids.length; ++k) {
            bytes32 id = book.ids[k];
            uint256 weight = book.weight[id];
            prefix += weight;
            // Per-source cumulative floors are monotone. Prefix differences are
            // used only at epoch end, when each can add at most one rounding unit.
            uint256 nextSold =
                Math.mulDiv(book.epochSold, flushEpoch ? prefix : weight, book.epochWeight);
            uint256 nextReceived =
                Math.mulDiv(book.epochReceived, flushEpoch ? prefix : weight, book.epochWeight);
            uint256 entitledSold = flushEpoch ? nextSold - previousSold : nextSold;
            uint256 entitledReceived = flushEpoch ? nextReceived - previousReceived : nextReceived;
            Completion memory c;
            c.sold = entitledSold - book.allocatedSold[id];
            c.received = entitledReceived - book.allocatedReceived[id];
            previousSold = nextSold;
            previousReceived = nextReceived;
            book.allocatedSold[id] = entitledSold;
            book.allocatedReceived[id] = entitledReceived;
            book.contribution[id] -= c.sold;
            book.remaining -= c.sold;
            book.pendingSold -= c.sold;
            book.pendingReceived -= c.received;
            if (c.sold == 0 && c.received == 0) continue;
            CycleSource storage source = self.cycleSources[id];
            if (self.donation[id]) {
                // A donation has no pool and no cycle: its proceeds mint to free cash as `DONATION` revenue.
                c.collateralId = seller.collateralId();
                c.source = RevenueSources.DONATION;
                if (c.received != 0) {
                    c.surplus = TreasuryFold.depositBacking(
                        ctx.registry, ctx.prusd, address(asset), book.reserve, c.received, 0
                    );
                }
            } else if (source.cycle != 0) {
                c.poolId = source.poolId;
                c.collateralId = source.collateralId;
                c.cycle = source.cycle;
                self.reservedCycle[id] -= c.sold;
                self.externalCycle[c.collateralId] -= c.sold;
                if (c.received != 0) {
                    c.surplus = TreasuryFold.depositBacking(
                        ctx.registry, ctx.prusd, address(asset), book.reserve, c.received, 0
                    );
                }
            } else {
                Lot storage lot = lots[id];
                c.poolId = lot.poolId;
                c.collateralId = lot.collateralId;
                self.reserved[id] -= c.sold;
                self.externalCollateral[lot.collateralId] -= c.sold;
                if (c.received != 0) {
                    TreasurySales.FoldSplit memory split = TreasuryFold.settleStable(
                        folds,
                        lot,
                        collateral,
                        TreasurySales.FoldSettlement(
                            id,
                            ctx.vault,
                            ctx.prusd,
                            ctx.registry,
                            address(asset),
                            c.sold,
                            c.received
                        ),
                        book.reserve
                    );
                    c.interest = split.interest;
                    c.surplus = split.surplus;
                } else {
                    lot.collateral -= c.sold;
                    collateral[lot.collateralId] -= c.sold;
                }
            }
            IPartialCowAccounting(address(this)).bookCowCompletion(c, address(asset), book.reserve);
            emit ICowLotEvents.CowSellerAllocated(owner, id, c.sold, c.received);
        }
        if (flushEpoch) {
            // All proceeds, including prefix rounding, must be booked before
            // any exhausted lot transfers its residual loss to reserves.
            lossInterest = TreasuryFold.finalizeLossBatch(
                folds, lots, book.ids, ctx.vault, ctx.prusd, ctx.registry
            );
            resetEpoch(book);
        }
    }

    function resetEpoch(SellerBook storage book) private {
        if (book.pendingSold != 0 || book.pendingReceived != 0) revert CustodyMismatch();
        // No old rounding entitlement may cross a contribution boundary.
        uint256 active;
        for (uint256 k; k < book.ids.length; ++k) {
            bytes32 id = book.ids[k];
            uint256 remaining = book.contribution[id];
            book.weight[id] = remaining;
            delete book.allocatedSold[id];
            delete book.allocatedReceived[id];
            if (remaining != 0) book.ids[active++] = id;
        }
        while (book.ids.length > active) book.ids.pop();
        book.epochWeight = book.remaining;
        book.epochSold = 0;
        book.epochReceived = 0;
    }

    function returnPartial(Ledger storage self, mapping(bytes32 => Lot) storage lots, address owner)
        private
    {
        SellerBook storage book = self.sellers[owner];
        if (book.reserve == address(0)) revert InvalidLotReservation();
        IPartialCowSeller seller = IPartialCowSeller(owner);
        if (seller.totalDebited() != book.debited) revert CustodyMismatch();
        IERC20 token = seller.sellToken();
        uint256 balance = token.balanceOf(address(this));
        uint256 returned = seller.returnCollateral();
        if (token.balanceOf(address(this)) != balance + returned || returned < book.remaining) {
            revert CustodyMismatch();
        }
        for (uint256 k; k < book.ids.length; ++k) {
            bytes32 id = book.ids[k];
            uint256 amount = book.contribution[id];
            CycleSource storage source = self.cycleSources[id];
            if (self.donation[id]) {
                self.idleDonation[seller.collateralId()] += amount;
            } else if (source.cycle == 0) {
                self.reserved[id] -= amount;
                self.externalCollateral[lots[id].collateralId] -= amount;
            } else {
                self.reservedCycle[id] -= amount;
                self.externalCycle[source.collateralId] -= amount;
            }
            delete book.contribution[id];
            emit ICowLotEvents.CowSellerReturned(owner, id, amount);
        }
        if (returned > book.remaining) {
            self.unclassified[address(token)] += returned - book.remaining;
            emit ICowLotEvents.CowSellerUnclassified(
                owner, address(token), returned - book.remaining
            );
        }
        delete book.ids;
        book.remaining = 0;
        resetEpoch(book);
    }

    function checkAvailable(Ledger storage self, bytes32 id, uint256 collateral, uint256 requested)
        internal
        view
    {
        uint256 available = collateral - self.reserved[id];
        if (requested > available) revert LotCollateralReserved(id, requested, available);
    }

    /// @notice A cycle's collateral still in the Treasury's own custody: its collateral less what that cycle
    ///         has at the configured seller (task 0294). The only figure a route sale may be sized from.
    function recoverableCycleCollateral(
        Ledger storage self,
        TreasurySales.CycleLedger storage cycles,
        uint256 pid,
        uint256 cycle
    ) external view returns (uint256) {
        uint256 collateral = cycles.collateral[pid][cycle];
        uint256 reserved = self.reservedCycle[keccak256(abi.encode("cow-cycle", pid, cycle))];
        return collateral > reserved ? collateral - reserved : 0;
    }
}

src/libraries/TreasuryFold.sol

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

import {TreasurySales, IFoldReserve, IRecoveryReserves} from "./TreasurySales.sol";
import {Lot} from "../types/LotTypes.sol";
import {IPRUSD} from "../interfaces/IPRUSD.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {StableReserveVault} from "../StableReserveVault.sol";
import {StableReserveRegistry} from "../registries/StableReserveRegistry.sol";
import {PsmAsset} from "../registries/PsmAssetRegistry.sol";
import {IOracleAdapter} from "../interfaces/IOracleAdapter.sol";
import {StableReserveMath} from "./StableReserveMath.sol";
import {SrvLossMath} from "./SrvLossMath.sol";
import {ICollateralRegistry} from "../interfaces/ICollateralRegistry.sol";
import {IGreaterMarketReference} from "../interfaces/IGreaterMarketReference.sol";
import {ISettlementPool7540} from "../interfaces/ISettlementPool7540.sol";

interface IFoldSaleContext {
    function vault() external view returns (address);
    function prusd() external view returns (address);
    function reserveRegistry() external view returns (address);
    function poolRegistry() external view returns (address);
    function collateralRegistry() external view returns (ICollateralRegistry);
    function greaterMarket() external view returns (IGreaterMarketReference);
    function hotswapSlippageBps() external view returns (uint256);
}

interface IFoldDebtVault {
    function settleFoldDebt(uint256 fid, uint256 principal, uint256 interest, bool migrated)
        external;
}

/// @notice Settle a folded lot as combined debt; P/I are attribution only. Runs in Treasury custody.
library TreasuryFold {
    using SafeERC20 for IERC20;
    error ResidualMismatch();
    error InvalidLossSource();
    error InvalidLossReserve(address asset);
    error InvalidSettlementCycle(address pool, uint256 cycle);
    error InsufficientLossReadGas();

    // ReservePriceAdapter forwards 1,000,000 gas to its resolver. Keep that read
    // independent of the caller's remaining gas before recognising an outage.
    uint256 private constant LOSS_PRICE_GAS = 1_100_000;

    /// @dev Shared pool checks moved out of Treasury for EIP-170; no storage or authority change.
    function validateSettlementCycle(
        address registry,
        address pool,
        address prusd,
        uint256 cycle,
        uint256 debt,
        bool includeCollateral
    ) external view returns (uint256 pid, uint256 collateralId) {
        pid = TreasurySales.settlementPoolId(registry, pool, prusd);
        ISettlementPool7540 p = ISettlementPool7540(pool);
        if (!p.settlementPending() || p.cycleId() != cycle || p.absorbedDebt() != debt || debt == 0)
        {
            revert InvalidSettlementCycle(pool, cycle);
        }
        if (includeCollateral) collateralId = p.collateralId();
    }

    event FoldLossAllocated(bytes32 indexed lotId, address indexed reserve, uint256 amount);
    event LotLossPending(bytes32 indexed lotId, uint256 principal, uint256 interest);
    event LotSaleNoFill(bytes32 indexed lotId, address indexed route, uint256 offered);
    event LotFoldNoFill(
        bytes32 indexed lotId, address indexed asset, address executor, uint256 offered
    );
    event LotSold(
        bytes32 indexed lotId,
        uint256 sold,
        uint256 proceeds,
        uint256 interestKept,
        uint256 principalBurned,
        uint256 tabRepaid,
        uint256 collateralLeft,
        uint256 principalLeft
    );

    struct Sale {
        bool stable;
        bytes32 id;
        address asset;
        address executor;
        uint256 offered;
    }

    /// @dev The existing instant exits share settlement and stay in this linked library for EIP-170.
    function sell(
        TreasurySales.FoldLedger storage ledger,
        Lot storage lot,
        mapping(uint256 => uint256) storage collateral,
        Sale memory sale,
        bytes calldata data
    ) external returns (uint256 sold, uint256 received, uint256 interest, uint256 surplus) {
        IFoldSaleContext t = IFoldSaleContext(address(this));
        if (!sale.stable) {
            address route;
            (sold, received, route) = TreasurySales.saleV4(
                TreasurySales.V4Sale(
                    t.poolRegistry(),
                    t.collateralRegistry(),
                    t.greaterMarket(),
                    t.hotswapSlippageBps(),
                    lot.poolId,
                    lot.collateralId,
                    t.prusd(),
                    sale.offered
                ),
                data
            );
            if (sold == 0) {
                emit LotSaleNoFill(sale.id, route, sale.offered);
                return (0, 0, 0, 0);
            }
        } else {
            (sold, received) = TreasurySales.saleSrv(
                t.reserveRegistry(), lot.collateralId, sale.asset, sale.executor, sale.offered, data
            );
            if (sold == 0) {
                emit LotFoldNoFill(sale.id, sale.asset, sale.executor, sale.offered);
                return (0, 0, 0, 0);
            }
        }
        TreasurySales.FoldSettlement memory s = TreasurySales.FoldSettlement(
            sale.id, t.vault(), t.prusd(), t.reserveRegistry(), sale.asset, sold, received
        );
        TreasurySales.FoldSplit memory f;
        if (!sale.stable) {
            f = settleDirect(ledger, lot, collateral, s);
            emit LotSold(sale.id, sold, received, 0, f.principal, 0, lot.collateral, lot.principal);
        } else {
            f = settleStable(ledger, lot, collateral, s, address(0));
        }
        (, uint256 lossInterest) =
            finalizeLoss(ledger, lot, sale.id, t.vault(), t.prusd(), t.reserveRegistry());
        emitPending(lot, sale.id);
        return (sold, received, f.interest + lossInterest, f.surplus);
    }

    struct LossSnapshot {
        bool available;
        address[] assets;
        address[] reserves;
        uint256[] values;
        uint256[] debts;
        uint256[] backing;
    }

    function allocateLoss(
        TreasurySales.FoldLedger storage ledger,
        Lot storage lot,
        bytes32 id,
        address vault,
        address prusd,
        address registry,
        uint256 maximum
    ) external returns (uint256 accepted, uint256 interest) {
        (accepted, interest) =
            _allocateLoss(ledger, lot, id, vault, prusd, registry, maximum, false);
        if (accepted != 0) emitPending(lot, id);
    }

    /// @dev Partial lots are not loss outcomes. Residual debt is the pending ledger;
    /// no second debt balance is created when a price is unavailable.
    function finalizeLoss(
        TreasurySales.FoldLedger storage ledger,
        Lot storage lot,
        bytes32 id,
        address vault,
        address prusd,
        address registry
    ) public returns (uint256 accepted, uint256 interest) {
        if (lot.poolId == 0) revert InvalidLossSource();
        if (lot.collateral != 0 || lot.principal + lot.interest == 0) return (0, 0);
        if (registry != address(0)) {
            (accepted, interest) =
                _allocateLoss(ledger, lot, id, vault, prusd, registry, type(uint256).max, true);
        }
    }

    /// @dev Proceeds for the entire epoch are booked before this shared snapshot.
    /// Each allocation updates the snapshot debt before the next lot uses it.
    function finalizeLossBatch(
        TreasurySales.FoldLedger storage ledger,
        mapping(bytes32 => Lot) storage lots,
        bytes32[] storage ids,
        address vault,
        address prusd,
        address registry
    ) external returns (uint256 interest) {
        LossSnapshot memory s;
        bool loaded;
        for (uint256 k; k < ids.length; ++k) {
            bytes32 id = ids[k];
            Lot storage lot = lots[id];
            // Donation and cycle source IDs have no folded lot.
            if (lot.poolId == 0 || lot.collateral != 0 || lot.principal + lot.interest == 0) {
                continue;
            }
            if (!loaded && registry != address(0)) {
                s = snapshot(StableReserveRegistry(registry), prusd, true);
                loaded = true;
            }
            if (s.available) {
                (, uint256 settledInterest) =
                    applyLoss(ledger, lot, id, vault, prusd, type(uint256).max, s);
                interest += settledInterest;
            }
            emitPending(lot, id);
        }
    }

    function emitPending(Lot storage lot, bytes32 id) private {
        if (lot.collateral == 0 && lot.principal + lot.interest != 0) {
            emit LotLossPending(id, lot.principal, lot.interest);
        }
    }

    function _allocateLoss(
        TreasurySales.FoldLedger storage ledger,
        Lot storage lot,
        bytes32 id,
        address vault,
        address prusd,
        address registry,
        uint256 maximum,
        bool toleratePriceOutage
    ) private returns (uint256 accepted, uint256 interest) {
        if (lot.poolId == 0 || lot.collateral != 0) {
            revert InvalidLossSource();
        }
        uint256 requested = Math.min(maximum, lot.principal + lot.interest);
        if (requested == 0) return (0, 0);
        LossSnapshot memory s =
            snapshot(StableReserveRegistry(registry), prusd, toleratePriceOutage);
        if (!s.available) return (0, 0);
        return applyLoss(ledger, lot, id, vault, prusd, requested, s);
    }

    function applyLoss(
        TreasurySales.FoldLedger storage ledger,
        Lot storage lot,
        bytes32 id,
        address vault,
        address prusd,
        uint256 maximum,
        LossSnapshot memory s
    ) private returns (uint256 accepted, uint256 interest) {
        uint256 requested = Math.min(maximum, lot.principal + lot.interest);
        (uint256[] memory allocations, uint256 retained) =
            SrvLossMath.allocate(s.values, s.debts, s.assets, requested);
        accepted = requested - retained;
        if (accepted == 0) return (0, 0);
        uint256 supply = IPRUSD(prusd).totalSupply();
        uint256 cash = IERC20(prusd).balanceOf(address(this));
        for (uint256 k; k < allocations.length; ++k) {
            uint256 amount = allocations[k];
            if (amount == 0) continue;
            StableReserveVault r = StableReserveVault(s.reserves[k]);
            r.acceptLoss(amount);
            if (r.debt() != s.debts[k] + amount || r.backing() != s.backing[k]) {
                revert ResidualMismatch();
            }
            s.debts[k] += amount;
            emit FoldLossAllocated(id, address(r), amount);
        }
        if (IPRUSD(prusd).totalSupply() != supply || IERC20(prusd).balanceOf(address(this)) != cash)
        {
            revert ResidualMismatch();
        }
        TreasurySales.FoldSplit memory f = split(accepted, lot.principal, lot.interest);
        reduce(ledger, lot, vault, id, f, true);
        return (accepted, f.interest);
    }

    function snapshot(StableReserveRegistry registry, address prusd, bool toleratePriceOutage)
        private
        view
        returns (LossSnapshot memory s)
    {
        s.available = true;
        if (registry.treasury() != address(this) || address(registry.prusd()) != prusd) {
            revert ResidualMismatch();
        }
        uint256 n = registry.assetCount();
        s.assets = new address[](n);
        s.reserves = new address[](n);
        s.values = new uint256[](n);
        s.debts = new uint256[](n);
        s.backing = new uint256[](n);
        for (uint256 k; k < n; ++k) {
            address asset = registry.assetAt(k);
            s.assets[k] = asset;
            PsmAsset memory a = registry.assetRegistry().getAsset(asset);
            if (!a.enabled) continue;
            StableReserveVault r = StableReserveVault(registry.reserveForAsset(asset));
            if (
                r.treasury() != address(this) || address(r.prusd()) != prusd
                    || address(r.backingAsset()) != asset || r.backingDecimals() != a.decimals
                    || IERC20Metadata(asset).decimals() != a.decimals || r.custodyDeficit() != 0
            ) revert InvalidLossReserve(asset);
            uint256 price =
                toleratePriceOutage ? lossPrice(a.oracle, asset) : IOracleAdapter(a.oracle).price();
            if (price == 0) {
                if (!toleratePriceOutage) revert InvalidLossReserve(asset);
                s.available = false;
            }
            s.reserves[k] = address(r);
            s.backing[k] = r.backing();
            s.debts[k] = r.debt();
            s.values[k] =
                Math.mulDiv(StableReserveMath.normalize(s.backing[k], a.decimals), price, 1e18);
        }
        return s;
    }

    function lossPrice(address oracle, address asset) private view returns (uint256 value) {
        bytes memory input = abi.encodeCall(IOracleAdapter.peek, ());
        bool ok;
        uint256 size;
        uint256 valid;
        // Allow cold-account CALL overhead in addition to EIP-150's retained gas.
        // An underfunded caller must revert, not manufacture a recoverable outage.
        if (gasleft() < LOSS_PRICE_GAS + LOSS_PRICE_GAS / 63 + 10_000) {
            revert InsufficientLossReadGas();
        }
        assembly ("memory-safe") {
            let out := mload(0x40)
            mstore(out, 0)
            mstore(add(out, 32), 0)
            ok := staticcall(LOSS_PRICE_GAS, oracle, add(input, 32), mload(input), out, 64)
            size := returndatasize()
            value := mload(out)
            valid := mload(add(out, 32))
        }
        // Empty failures (including OOG), malformed data and unexpected errors
        // are fatal. No allocation write occurs before all snapshots succeed.
        if (!ok || size != 64 || valid > 1 || (valid == 1) != (value != 0)) {
            revert InvalidLossReserve(asset);
        }
    }

    event FoldDebtSettled(
        bytes32 indexed lotId, bool migrated, uint256 principal, uint256 interest
    );
    event LotFolded(
        bytes32 indexed lotId,
        address indexed asset,
        uint256 sold,
        uint256 backingIn,
        uint256 interestMinted,
        uint256 principalMigrated,
        uint256 surplusMinted,
        uint256 tabRepaid,
        uint256 collateralLeft,
        uint256 principalLeft
    );
    event FoldFacilitySettled(
        bytes32 indexed lotId,
        uint256 indexed facilityId,
        bool migrated,
        uint256 principal,
        uint256 interest
    );

    function split(uint256 value, uint256 principal, uint256 interest)
        internal
        pure
        returns (TreasurySales.FoldSplit memory f)
    {
        uint256 debt = principal + interest;
        uint256 applied = Math.min(value, debt);
        f.principal = debt == 0 ? 0 : Math.mulDiv(applied, principal, debt);
        f.interest = applied - f.principal;
        f.surplus = value - applied;
    }

    function settleStable(
        TreasurySales.FoldLedger storage ledger,
        Lot storage lot,
        mapping(uint256 => uint256) storage collateral,
        TreasurySales.FoldSettlement memory s,
        address committedReserve
    ) public returns (TreasurySales.FoldSplit memory f) {
        // Only authenticated asynchronous fills supply a previously admitted reserve.
        // New synchronous sales still require admission in this same transaction.
        uint256 value = s.received * 10
            ** (18
                - IFoldReserve(
                        committedReserve == address(0)
                            ? IRecoveryReserves(s.reserveRegistry).validateDeposit(s.asset)
                            : committedReserve
                    )
                    .backingDecimals());
        f = split(value, lot.principal, lot.interest);
        _depositBacking(
            s.reserveRegistry,
            s.prusd,
            s.asset,
            committedReserve,
            s.received,
            f.principal + f.interest
        );
        lot.collateral -= s.sold;
        collateral[lot.collateralId] -= s.sold;
        reduce(ledger, lot, s.vault, s.id, f, true);
        emit LotFolded(
            s.id,
            s.asset,
            s.sold,
            s.received,
            0,
            f.principal,
            f.surplus,
            0,
            lot.collateral,
            lot.principal
        );
    }

    /// @dev Shared exact backing checks for folded debt migration and cycle recovery.
    function depositBacking(
        address registry,
        address prusd,
        address asset,
        address committedReserve,
        uint256 received,
        uint256 unminted
    ) external returns (uint256 minted) {
        return _depositBacking(registry, prusd, asset, committedReserve, received, unminted);
    }

    function _depositBacking(
        address registry,
        address prusd,
        address asset,
        address committedReserve,
        uint256 received,
        uint256 unminted
    ) private returns (uint256 minted) {
        address reserve = committedReserve == address(0)
            ? IRecoveryReserves(registry).validateDeposit(asset)
            : committedReserve;
        if (committedReserve != address(0)) {
            StableReserveVault bound = StableReserveVault(reserve);
            if (
                bound.treasury() != address(this) || address(bound.prusd()) != prusd
                    || address(bound.backingAsset()) != asset
                    || StableReserveRegistry(registry).reserveForAsset(asset) != reserve
            ) revert ResidualMismatch();
        }
        IFoldReserve r = IFoldReserve(reserve);
        uint256 value = received * 10 ** (18 - r.backingDecimals());
        uint256 cash = IERC20(prusd).balanceOf(address(this));
        uint256 supply = IPRUSD(prusd).totalSupply();
        uint256 debt = r.debt();
        uint256 backing = r.backing();
        IERC20(asset).forceApprove(reserve, received);
        minted = r.depositFromTreasuryMigrating(received, unminted);
        IERC20(asset).forceApprove(reserve, 0);
        if (
            minted != value - unminted || IERC20(prusd).balanceOf(address(this)) != cash + minted
                || IPRUSD(prusd).totalSupply() != supply + minted || r.debt() != debt + value
                || r.backing() != backing + received
        ) revert ResidualMismatch();
    }

    function settleDirect(
        TreasurySales.FoldLedger storage ledger,
        Lot storage lot,
        mapping(uint256 => uint256) storage collateral,
        TreasurySales.FoldSettlement memory s
    ) public returns (TreasurySales.FoldSplit memory f) {
        f = split(s.received, lot.principal, lot.interest);
        uint256 burn = f.principal + f.interest;
        if (burn != 0) {
            IPRUSD token = IPRUSD(s.prusd);
            uint256 supply = token.totalSupply();
            uint256 cash = token.balanceOf(address(this));
            token.burn(address(this), burn);
            if (
                token.totalSupply() != supply - burn
                    || token.balanceOf(address(this)) != cash - burn
            ) {
                revert ResidualMismatch();
            }
        }
        lot.collateral -= s.sold;
        collateral[lot.collateralId] -= s.sold;
        reduce(ledger, lot, s.vault, s.id, f, false);
    }

    /// @dev Neither migration nor burning an interest-origin component is interest income.
    function reduce(
        TreasurySales.FoldLedger storage ledger,
        Lot storage lot,
        address vault,
        bytes32 id,
        TreasurySales.FoldSplit memory f,
        bool migrated
    ) internal {
        uint256 totalP = lot.principal;
        uint256 totalI = lot.interest;
        lot.principal -= f.principal;
        lot.interest -= f.interest;
        uint256 seenP;
        uint256 seenI;
        uint256[] storage ids = ledger.facilities[id];
        for (uint256 k; k < ids.length; ++k) {
            uint256 fid = ids[k];
            TreasurySales.FacilityBalance storage balance = ledger.debt[id][fid];
            uint256 p = portion(f.principal, seenP, balance.principal, totalP);
            uint256 i = portion(f.interest, seenI, balance.interest, totalI);
            seenP += balance.principal;
            seenI += balance.interest;
            balance.principal -= p;
            balance.interest -= i;
            if (p == 0 && i == 0) continue;
            IFoldDebtVault(vault).settleFoldDebt(fid, p, i, migrated);
            emit FoldFacilitySettled(id, fid, migrated, p, i);
        }
        if (seenP != totalP || seenI != totalI) revert ResidualMismatch();
        emit FoldDebtSettled(id, migrated, f.principal, f.interest);
    }

    function portion(uint256 amount, uint256 seen, uint256 weight, uint256 total)
        private
        pure
        returns (uint256)
    {
        if (amount == 0) return 0;
        return Math.mulDiv(amount, seen + weight, total) - Math.mulDiv(amount, seen, total);
    }
}

src/libraries/TreasurySales.sol

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

import {PricingEvidence, ISalePricingEvents} from "./SalePricing.sol";

import {IArbBuyer} from "../interfaces/IArbBuyer.sol";
import {IStabilityPoolRegistry} from "../interfaces/IStabilityPoolRegistry.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {Roles} from "./Roles.sol";

interface ILiquidationCycleSource {
    function liquidationCycleId() external view returns (uint256);
    function liquidationCycleOpen() external view returns (bool);
}

interface ITreasuryBuybackBinding {
    function treasury() external view returns (address);
    function prusd() external view returns (address);
}

/// @dev The Treasury getters the arbitrage leg reads in its delegatecall context (task 0201, EIP-170).
interface ITreasuryArbView {
    function poolRegistry() external view returns (address);
    function reserveRegistry() external view returns (address);
    function prusd() external view returns (address);
    function greaterMarket() external view returns (address);
    function spendableCash() external view returns (uint256);
}

interface ICycleArbitrage {
    function cycleArbitrage(
        uint256 cid,
        uint256 budget,
        address asset,
        address executor,
        bytes calldata data
    ) external returns (uint256 spent, uint256 minted);
}

/// @dev The pool registry's arbitrage route getter (task 0201): `WarehousePoolRegistry.arbRoute`.
interface IArbRoutes {
    function arbRoute(uint256 poolId)
        external
        view
        returns (address buyer, uint256 maxSpend, uint16 gapBps, uint16 minProfitBps);
}
import {IGreaterMarketReference} from "../interfaces/IGreaterMarketReference.sol";
import {Lot, LotHandover} from "../types/LotTypes.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IFloorSettlementExecutor} from "../interfaces/IFloorSettlementExecutor.sol";
import {ICollateralRegistry} from "../interfaces/ICollateralRegistry.sol";
import {CollateralConfig} from "../types/ProtocolTypes.sol";
import {WarehouseSourceAuth} from "../WarehouseSourceAuth.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IWarehouseCycleSource} from "../interfaces/IWarehouseCycleSource.sol";
import {ISettlementPool7540} from "../interfaces/ISettlementPool7540.sol";

interface IResidualSource {
    function pool() external view returns (address);
    function treasury() external view returns (address);
    function residualQuote() external view returns (uint256 cycle, uint256 amount, uint256 stop);
    function collateralToken() external view returns (address);
    function collateralDecimals() external view returns (uint8);
    function collateralId() external view returns (uint256);
}

interface IFoldReserve {
    function depositFromTreasuryMigrating(uint256 amount, uint256 unminted)
        external
        returns (uint256);
    function backingDecimals() external view returns (uint8);
    function backing() external view returns (uint256);
    function debt() external view returns (uint256);
}

interface IRecoveryReserves {
    function validateRecoveryAndRecord(
        uint256 cid,
        address asset,
        address executor,
        uint256 offered
    ) external returns (address token, address pool, uint8 decimals, uint256 floor);
    function validateDeposit(address asset) external view returns (address reserve);
    function depositState(address asset, uint256 incoming) external view returns (bytes32);
}

interface IReserveRegistryBinding {
    function treasury() external view returns (address);
    function prusd() external view returns (address);
    function assetRegistry() external view returns (address);
}

interface IRecoveryReserve {
    function depositFromTreasury(uint256 amount) external returns (uint256);
    function backingDecimals() external view returns (uint8);
}

interface ISettlementPaymentReceiver {
    function receiveRecoveryRepayment(uint256 amount) external;
    function repairFromTreasury(uint256 amount) external;
}

interface ILotRouteCheck {
    function validateLotRouteWithPricing(uint256 cid, address asset, address executor)
        external
        view
        returns (address token, uint8 decimals, uint256 floor, PricingEvidence.Quote memory q);
    function validateLotRoute(uint256 cid, address asset, address executor)
        external
        view
        returns (address token, uint8 decimals, uint256 floor);
}

interface ISaleRoutes {
    function saleRoute(uint256 poolId) external view returns (address);
}

/// @notice The Treasury's collateral sales, linked at deploy (task 0191; Bevan chose a linked library over trimming
///         for EIP-170 room). External library functions run by DELEGATECALL, so every transfer and executor call is
///         made AS the Treasury: executors, reserves and tokens see the Treasury as the caller. Fixed at deploy; no
///         proxy and nothing to upgrade. Owns no separate custody; cycle bookkeeping uses explicitly passed
///         Treasury storage, like the existing lot bookkeeping.
library TreasurySales {
    struct BuybackBinding {
        address target;
    }

    error BuybackBindingInvalid();
    event BuybackSet(address indexed buyback);
    event BuybackFunded(address indexed buyback, uint256 amount);

    /// @dev Treasury's admin-gated setup entrypoint delegates here to keep its runtime within the size budget.
    function bindBuyback(BuybackBinding storage binding, address candidate, address prusd)
        external
    {
        if (
            binding.target != address(0) || candidate.code.length == 0
                || ITreasuryBuybackBinding(candidate).treasury() != address(this)
                || ITreasuryBuybackBinding(candidate).prusd() != prusd
        ) revert BuybackBindingInvalid();
        binding.target = candidate;
        emit BuybackSet(candidate);
    }

    function payBuyback(BuybackBinding storage binding, address prusd, uint256 amount) external {
        if (msg.sender != binding.target) revert BuybackBindingInvalid();
        IERC20(prusd).safeTransfer(msg.sender, amount);
        emit BuybackFunded(msg.sender, amount);
    }

    error PoolRegistryNotSet();
    error NotRegisteredPool(address pool);

    /// @dev Shared settlement authentication, unchanged; delegatecall preserves Treasury identity.
    function settlementPoolId(address registry, address pool, address prusd)
        external
        view
        returns (uint256 pid)
    {
        if (registry == address(0)) revert PoolRegistryNotSet();
        IStabilityPoolRegistry pools = IStabilityPoolRegistry(registry);
        pid = pools.poolIdForPool(pool);
        if (pid == 0 || pools.getPool(pid).pool != pool) revert NotRegisteredPool(pool);
        ISettlementPool7540 p = ISettlementPool7540(pool);
        if (p.asset() != prusd || p.share() != pool || p.settlementLedger() != address(this)) {
            revert NotRegisteredPool(pool);
        }
    }

    using SafeERC20 for IERC20;
    using EnumerableSet for EnumerableSet.UintSet;

    // Attribution beneath Treasury.seizedInventory; these quantities are not additional custody.
    struct CycleLedger {
        mapping(uint256 poolId => mapping(uint256 liquidationCycleId => uint256)) collateral;
        mapping(uint256 poolId => uint256) active;
        mapping(uint256 poolId => uint256) tab;
        mapping(uint256 poolId => EnumerableSet.UintSet) held;
        mapping(uint256 poolId => mapping(uint256 liquidationCycleId => uint256)) cash;
        mapping(uint256 poolId => uint256) settledBite;
        mapping(uint256 poolId => uint256) closed;
        uint256 totalCash;
        mapping(uint256 poolId => mapping(uint256 liquidationCycleId => uint256)) revenue;
        uint256 totalRevenue;
    }

    struct CycleRecovery {
        uint256 pid;
        uint256 id;
        uint256 cid;
        uint256 sold;
        uint256 minted;
        uint256 outstanding;
        address asset;
        address executor;
    }

    // Fixed inner allowance plus an uncaught outer floor prevents cheap, always-skipped gas estimates.
    uint256 internal constant CYCLE_ARB_GAS = 3_000_000;
    uint256 internal constant CYCLE_ARB_TAIL_GAS = 750_000;
    error CycleArbitrageGasInsufficient();
    error CycleArbitrageNoFill();
    event CycleArbitrageExecuted(
        uint256 indexed poolId, uint256 indexed liquidationCycleId, uint256 spent, uint256 minted
    );
    event CycleArbitrageSkipped(
        uint256 indexed poolId, uint256 indexed liquidationCycleId, bytes reason
    );

    struct FacilityBalance {
        uint256 principal;
        uint256 interest;
        bool assigned;
    }

    struct FoldLedger {
        mapping(bytes32 => uint256[]) facilities;
        mapping(bytes32 => mapping(uint256 => FacilityBalance)) debt;
    }

    struct FoldContext {
        address vault;
        ICollateralRegistry collateralRegistry;
        IGreaterMarketReference greaterMarket;
        uint256 collateralId;
        uint256 poolId;
        uint256 externalCollateral;
    }

    struct FoldSettlement {
        bytes32 id;
        address vault;
        address prusd;
        address reserveRegistry;
        address asset;
        uint256 sold;
        uint256 received;
    }

    struct ResidualContext {
        address pool;
        uint256 poolId;
        uint256 collateralId;
        uint256 bite;
        uint256 amount;
        uint256 stop;
    }

    /// @dev Read-only admission; replay protection and purchase accounting remain in the Treasury.
    function residualContext(
        mapping(address => address) storage settlementSource,
        address poolRegistry,
        address vault,
        address prusd
    ) external view returns (ResidualContext memory r) {
        IResidualSource w = IResidualSource(msg.sender);
        r.pool = w.pool();
        if (settlementSource[r.pool] != msg.sender || w.treasury() != address(this)) {
            revert ResidualMismatch();
        }
        r.poolId = IStabilityPoolRegistry(poolRegistry).poolIdForPool(r.pool);
        if (r.poolId == 0 || IStabilityPoolRegistry(poolRegistry).getPool(r.poolId).pool != r.pool)
        {
            revert ResidualMismatch();
        }
        r.collateralId = ISettlementPool7540(r.pool).collateralId();
        (r.bite, r.amount, r.stop) = w.residualQuote();
        checkResidual(vault, prusd, r.pool, msg.sender, r.collateralId, r.bite, r.amount, r.stop);
    }

    event LiquidationCyclePurchase(
        uint256 indexed poolId,
        uint256 indexed liquidationCycleId,
        uint256 indexed biteId,
        uint256 collateral,
        uint256 cash,
        uint256 tab,
        uint256 collateralHeld,
        uint256 tabOutstanding
    );
    event LiquidationCycleRecovery(
        uint256 indexed poolId,
        uint256 indexed liquidationCycleId,
        uint256 sold,
        uint256 minted,
        uint256 tabRepaid,
        uint256 collateralHeld,
        uint256 currentTabOutstanding
    );
    event LiquidationCycleTabClosed(
        uint256 indexed poolId,
        uint256 indexed liquidationCycleId,
        uint256 tabReclassified,
        uint256 collateralHeld
    );
    event LiquidationCycleTabAdjusted(
        uint256 indexed poolId,
        uint256 indexed liquidationCycleId,
        uint256 writtenOff,
        uint256 tabOutstanding
    );
    event LiquidationCycleCashReserved(
        uint256 indexed poolId, uint256 indexed cycle, uint256 amount
    );
    event LiquidationCycleCashApplied(
        uint256 indexed poolId, uint256 indexed cycle, uint256 amount
    );
    event LiquidationCycleCashReleased(
        uint256 indexed poolId, uint256 indexed cycle, uint256 amount
    );

    function recordCyclePurchase(
        CycleLedger storage c,
        address source,
        uint256 pid,
        uint256 bite,
        uint256 amount,
        uint256 cash,
        uint256 tab
    ) external {
        ILiquidationCycleSource w = ILiquidationCycleSource(source);
        uint256 id = w.liquidationCycleId();
        if (
            id <= c.closed[pid] || !w.liquidationCycleOpen()
                || (c.active[pid] != 0 && c.active[pid] != id)
        ) {
            revert ResidualMismatch();
        }
        c.active[pid] = id;
        c.collateral[pid][id] += amount;
        c.held[pid].add(id);
        c.tab[pid] += tab;
        emit LiquidationCyclePurchase(
            pid, id, bite, amount, cash, tab, c.collateral[pid][id], c.tab[pid]
        );
    }

    function closeCycle(
        CycleLedger storage c,
        address vault,
        address source,
        address pool,
        uint256 pid,
        uint256 id
    ) external {
        _checkCycleSource(vault, source, pool, id, false);
        if (
            id <= c.closed[pid] || (c.active[pid] != 0 && c.active[pid] != id)
                || ISettlementPool7540(pool).settlementPending()
                || (c.tab[pid] != 0 && c.cash[pid][id] != 0)
        ) revert ResidualMismatch();
        uint256 released = c.cash[pid][id];
        c.totalRevenue -= c.revenue[pid][id];
        delete c.revenue[pid][id];
        c.totalCash -= released;
        delete c.cash[pid][id];
        c.closed[pid] = id;
        uint256 tab = c.tab[pid];
        c.tab[pid] = 0;
        c.active[pid] = 0;
        emit LiquidationCycleTabClosed(pid, id, tab, c.collateral[pid][id]);
        emit LiquidationCycleCashReleased(pid, id, released);
    }

    /// @dev Called only after the pool's settlement callback has returned and booked its TAB.
    function settleCycleCash(
        CycleLedger storage c,
        address vault,
        address source,
        address pool,
        uint256 pid,
        uint256 id,
        uint256 bite,
        uint256 outstanding
    ) external returns (uint256 paid, uint256 revenuePaid) {
        _checkCycleSource(vault, source, pool, id, true);
        ISettlementPool7540 p = ISettlementPool7540(pool);
        if (
            id <= c.closed[pid] || bite <= c.settledBite[pid] || p.cycleId() != bite
                || p.settlementPending() || (c.active[pid] != 0 && c.active[pid] != id)
                || p.tabReceivable() + p.claimTab() + p.earningsTab() != outstanding
        ) revert ResidualMismatch();
        c.settledBite[pid] = bite;
        (paid, revenuePaid) = _takeCycleCash(c, pid, id, outstanding);
    }

    function _checkCycleSource(address vault, address source, address pool, uint256 id, bool open)
        private
        view
    {
        IWarehouseCycleSource w = IWarehouseCycleSource(source);
        if (
            msg.sender != source || w.pool() != pool || w.treasury() != address(this)
                || source
                    != WarehouseSourceAuth.canonicalFromVault(
                        vault, ISettlementPool7540(pool).collateralId()
                    ) || ILiquidationCycleSource(source).liquidationCycleId() != id
                || ILiquidationCycleSource(source).liquidationCycleOpen() != open
        ) revert ResidualMismatch();
    }

    function _takeCycleCash(CycleLedger storage c, uint256 pid, uint256 id, uint256 outstanding)
        private
        returns (uint256 paid, uint256 revenuePaid)
    {
        paid = Math.min(c.cash[pid][id], outstanding);
        uint256 surplus = c.cash[pid][id] - c.revenue[pid][id];
        revenuePaid = paid - Math.min(paid, surplus);
        c.revenue[pid][id] -= revenuePaid;
        c.totalRevenue -= revenuePaid;
        c.cash[pid][id] -= paid;
        c.totalCash -= paid;
        c.tab[pid] -= Math.min(c.tab[pid], paid);
        if (paid != 0) emit LiquidationCycleCashApplied(pid, id, paid);
    }

    function recordCycleRecovery(CycleLedger storage c, CycleRecovery memory r, bytes calldata data)
        external
        returns (uint256 repaid, uint256 revenuePaid)
    {
        c.collateral[r.pid][r.id] -= r.sold;
        if (c.collateral[r.pid][r.id] == 0) c.held[r.pid].remove(r.id);
        // A no-fill caller returns without making a pool payment; leave retained cash for the hook.
        // A pooled fill can allocate proceeds to a cycle whose collateral share rounds to zero (DEF-679).
        if (c.active[r.pid] == r.id && (r.sold != 0 || r.minted != 0)) {
            c.cash[r.pid][r.id] += r.minted;
            c.totalCash += r.minted;
            if (r.minted != 0) emit LiquidationCycleCashReserved(r.pid, r.id, r.minted);
            _tryCycleArbitrage(c, r, data);
            (repaid, revenuePaid) = _takeCycleCash(c, r.pid, r.id, r.outstanding);
        }
        emit LiquidationCycleRecovery(
            r.pid, r.id, r.sold, r.minted, repaid, c.collateral[r.pid][r.id], c.tab[r.pid]
        );
    }

    function _tryCycleArbitrage(CycleLedger storage c, CycleRecovery memory r, bytes calldata data)
        private
    {
        ITreasuryArbView t = ITreasuryArbView(address(this));
        address routes = t.poolRegistry();
        (address buyer,,,) = IArbRoutes(routes).arbRoute(r.pid);
        uint256 budget = c.cash[r.pid][r.id];
        if (
            budget == 0 || buyer == address(0)
                || IStabilityPoolRegistry(routes).poolForCollateral(r.cid) != r.pid
        ) return;
        // Pooled seller proceeds arrive without a synchronous executor: report the skipped leg (DEF-680).
        if (r.executor == address(0)) {
            emit CycleArbitrageSkipped(r.pid, r.id, "");
            return;
        }
        bytes memory input = abi.encodeCall(
            ICycleArbitrage.cycleArbitrage, (r.cid, budget, r.asset, r.executor, data)
        );
        uint256 beforeCash = IERC20(t.prusd()).balanceOf(address(this));
        // Include EIP-150 headroom and a repayment reserve. This check is deliberately outside the caught frame.
        if (gasleft() < CYCLE_ARB_GAS + (CYCLE_ARB_GAS + 62) / 63 + CYCLE_ARB_TAIL_GAS) {
            revert CycleArbitrageGasInsufficient();
        }
        bool ok;
        uint256 spent;
        uint256 minted;
        bytes4 reason;
        uint256 returned;
        // Bound returndata copying even when an admitted executor reverts with a large payload.
        assembly ("memory-safe") {
            let output := mload(0x40)
            mstore(output, 0)
            mstore(add(output, 32), 0)
            ok := call(CYCLE_ARB_GAS, address(), 0, add(input, 32), mload(input), output, 64)
            returned := returndatasize()
            spent := mload(output)
            minted := mload(add(output, 32))
            reason := mload(output)
        }
        if (!ok) {
            emit CycleArbitrageSkipped(
                r.pid, r.id, returned >= 4 ? abi.encodePacked(reason) : bytes("")
            );
            return;
        }
        if (
            returned != 64 || spent > budget || minted < spent
                || IERC20(t.prusd()).balanceOf(address(this)) != beforeCash + minted - spent
        ) {
            revert ResidualMismatch();
        }
        if (spent == 0 && minted == 0) {
            emit CycleArbitrageSkipped(r.pid, r.id, abi.encodePacked(CycleArbitrageNoFill.selector));
            return;
        }
        uint256 profit = minted - spent;
        c.cash[r.pid][r.id] += profit;
        c.totalCash += profit;
        c.revenue[r.pid][r.id] += profit;
        c.totalRevenue += profit;
        emit CycleArbitrageExecuted(r.pid, r.id, spent, minted);
    }

    function clampCycleTab(CycleLedger storage c, uint256 pid, uint256 total) external {
        // The existing final-exit penalty write-off consumes old TAB before current TAB.
        uint256 current = c.tab[pid];
        if (current > total) {
            c.tab[pid] = total;
            emit LiquidationCycleTabAdjusted(pid, c.active[pid], current - total, total);
        }
    }

    /// @dev Same signature as the Treasury's error, so a failed receipt check reverts exactly as before.
    error ResidualMismatch();
    error SettlementSourceInvalid();
    error CollateralRegistryNotSet();

    function checkReserveRegistry(address registry, address prusd, address assets) external view {
        IReserveRegistryBinding r = IReserveRegistryBinding(registry);
        if (
            registry.code.length == 0 || r.treasury() != address(this) || r.prusd() != prusd
                || r.assetRegistry() != assets
        ) revert ResidualMismatch();
    }

    function checkResidual(
        address vault,
        address prusd,
        address pool,
        address source,
        uint256 cid,
        uint256 bite,
        uint256 amount,
        uint256 stop
    ) public view {
        ISettlementPool7540 sp = ISettlementPool7540(pool);
        if (
            amount == 0 || stop == 0 || !sp.settlementPending() || sp.cycleId() != bite
                || cid != IResidualSource(source).collateralId()
                || sp.settlementLedger() != address(this) || sp.asset() != prusd
                || source != WarehouseSourceAuth.canonicalFromVault(vault, cid)
        ) revert ResidualMismatch();
    }

    /// @notice How a fold's jUSD value splits: interest minted, principal migrated, surplus minted.
    struct FoldSplit {
        uint256 interest;
        uint256 principal;
        uint256 surplus;
    }

    struct Balances {
        uint256 cash;
        uint256 debt;
        uint256 backing;
    }

    struct Receipt {
        uint256 beforeToken;
        uint256 beforeOutput;
        uint256 claimedSold;
        uint256 returned;
        uint256 claimedOutput;
    }

    /// @notice Sell `offered` collateral through an executor at no worse than `floor` (output units per whole
    ///         collateral). Sold and received amounts are MEASURED from the caller's own balances and must match
    ///         what the executor reports; unsold collateral must come back.
    function sellThrough(
        address token,
        address output,
        address executor,
        uint256 offered,
        uint256 floor,
        bytes calldata data
    ) external returns (uint256 sold, uint256 received) {
        return _sellThrough(token, output, executor, offered, floor, data);
    }

    function _sellThrough(
        address token,
        address output,
        address executor,
        uint256 offered,
        uint256 floor,
        bytes calldata data
    ) private returns (uint256 sold, uint256 received) {
        Receipt memory r;
        r.beforeToken = IERC20(token).balanceOf(address(this));
        r.beforeOutput = IERC20(output).balanceOf(address(this));
        uint256 executorBefore = IERC20(token).balanceOf(executor);
        IERC20(token).safeTransfer(executor, offered);
        if (IERC20(token).balanceOf(executor) != executorBefore + offered) {
            revert ResidualMismatch();
        }
        (r.claimedSold, r.returned, r.claimedOutput) =
            IFloorSettlementExecutor(executor).executeAtFloor(token, offered, floor, data);
        sold = r.beforeToken - IERC20(token).balanceOf(address(this));
        received = IERC20(output).balanceOf(address(this)) - r.beforeOutput;
        if (
            sold > offered || r.claimedSold != sold || r.returned != offered - sold
                || r.claimedOutput != received
        ) revert ResidualMismatch();
        emit ISalePricingEvents.SaleMeasured(executor, sold, received);
    }

    /// @notice A pool's single sale route (from the SP registry) and the lowest acceptable jUSD per whole collateral:
    ///         market price less the slippage tolerance. Reverts if either is unavailable.
    function _lotRoute(
        address poolRegistry,
        ICollateralRegistry collateralRegistry,
        IGreaterMarketReference greaterMarket,
        uint256 slippageBps,
        uint256 poolId,
        uint256 collateralId
    ) private view returns (address route, address token, uint256 unit, uint256 floor, uint256 g) {
        route = ISaleRoutes(poolRegistry).saleRoute(poolId);
        CollateralConfig memory c = collateralRegistry.getCollateral(collateralId);
        bool valid;
        (g, valid) = greaterMarket.greaterMarketPrice(collateralId);
        if (route == address(0) || !valid || g == 0 || slippageBps == 0 || slippageBps > 10_000) {
            revert ResidualMismatch();
        }
        token = c.token;
        unit = 10 ** c.decimals;
        floor = Math.mulDiv(g, 10_000 - slippageBps, 10_000, Math.Rounding.Ceil);
    }

    /// @dev Caller retains authorization, cash reservation and ledger updates before this measured payment.
    function payRecovery(address prusd, address pool, uint256 amount, uint256 beforeCash) external {
        IERC20(prusd).forceApprove(pool, amount);
        ISettlementPaymentReceiver(pool).receiveRecoveryRepayment(amount);
        IERC20(prusd).forceApprove(pool, 0);
        if (IERC20(prusd).balanceOf(address(this)) != beforeCash - amount) {
            revert ResidualMismatch();
        }
    }

    function payRepair(address prusd, address reserve, uint256 amount, uint256 beforeCash)
        external
    {
        IERC20(prusd).forceApprove(reserve, amount);
        ISettlementPaymentReceiver(reserve).repairFromTreasury(amount);
        IERC20(prusd).forceApprove(reserve, 0);
        if (IERC20(prusd).balanceOf(address(this)) != beforeCash - amount) {
            revert ResidualMismatch();
        }
    }

    /// @notice The takeover mark (Tim's rules §3.7, marked at current prices): the part of a lot's principal its
    ///         collateral does not cover at the market price. Zero, with price zero, if no valid price is available.
    function markShortfall(
        IGreaterMarketReference greaterMarket,
        ICollateralRegistry collateralRegistry,
        uint256 collateralId,
        uint256 collateral,
        uint256 principal,
        uint256 interest
    ) public view returns (uint256 marked, uint256 price) {
        try greaterMarket.greaterMarketPrice(collateralId) returns (uint256 g, bool valid) {
            if (!valid || g == 0) return (0, 0);
            price = g;
        } catch {
            return (0, 0);
        }
        uint256 value = Math.mulDiv(
            collateral, price, 10 ** collateralRegistry.getCollateral(collateralId).decimals
        );
        uint256 owed = principal + interest;
        marked = value >= owed ? 0 : Math.min(principal, owed - value);
    }

    /// @notice Inputs for a Treasury lot's V4 sale (task 0191).
    struct V4Sale {
        address poolRegistry;
        ICollateralRegistry collateralRegistry;
        IGreaterMarketReference greaterMarket;
        uint256 slippageBps;
        uint256 poolId;
        uint256 collateralId;
        address prusd;
        uint256 offered;
    }

    /// @notice A lot's V4 sale through its SP's route at no worse than the market price less the tolerance.
    ///         Returns zero sold and proceeds on a no-fill; reverts if a fill cleared below the floor.
    function saleV4(V4Sale calldata v, bytes calldata data)
        external
        returns (uint256 sold, uint256 proceeds, address route)
    {
        address token;
        uint256 unit;
        uint256 floor;
        uint256 g;
        (route, token, unit, floor, g) = _lotRoute(
            v.poolRegistry,
            v.collateralRegistry,
            v.greaterMarket,
            v.slippageBps,
            v.poolId,
            v.collateralId
        );
        PricingEvidence.record(
            route, token, v.prusd, floor, v.offered, PricingEvidence.Quote(g, 0, v.slippageBps, 0)
        );
        (sold, proceeds) = _sellThrough(token, v.prusd, route, v.offered, floor, data);
        _checkFill(sold, proceeds, floor, unit);
    }

    /// @notice A lot's SRV-fold sale for a stablecoin through one of the Treasury's recovery routes (task 0192):
    ///         the reserve registry's lot-route check (route, executor binding, depeg gate, floor).
    function saleSrv(
        address reserveRegistry,
        uint256 collateralId,
        address asset,
        address executor,
        uint256 offered,
        bytes calldata data
    ) external returns (uint256 sold, uint256 received) {
        (address token, uint8 decimals, uint256 floor, PricingEvidence.Quote memory q) = ILotRouteCheck(
                reserveRegistry
            )
            .validateLotRouteWithPricing(collateralId, asset, executor);
        PricingEvidence.record(executor, token, asset, floor, offered, q);
        (sold, received) = _sellThrough(token, asset, executor, offered, floor, data);
        _checkFill(sold, received, floor, 10 ** decimals);
    }

    function _checkFill(uint256 sold, uint256 received, uint256 floor, uint256 unit) private pure {
        if (sold == 0
                ? received != 0
                : received < Math.mulDiv(sold, floor, unit, Math.Rounding.Ceil)) {
            revert ResidualMismatch();
        }
    }

    /// @notice Inputs for an unwind-inventory SRV recovery sale (moved here unchanged for EIP-170, task 0192).
    struct RecoverySale {
        address reserveRegistry;
        uint256 collateralId;
        address asset;
        address executor;
        uint256 offered;
        uint256 held;
        uint256 lotCollateral;
        uint256 externalCollateral;
    }

    /// @notice Sell unwind inventory for a stablecoin, check the floor, and deposit it all into the reserve, which
    ///         mints one-for-one (warehouse v2 §3.5). The deposit is checked against the registry's exact state
    ///         fingerprint before and after. Returns zeros on a no-fill.
    function recoverySale(
        mapping(address => address) storage sources,
        RecoverySale calldata v,
        bytes calldata data
    )
        external
        returns (uint256 sold, uint256 received, uint256 minted, address reserve, address pool)
    {
        IRecoveryReserves registry = IRecoveryReserves(v.reserveRegistry);
        address token;
        uint8 decimals;
        uint256 floor;
        (token, pool, decimals, floor) =
            registry.validateRecoveryAndRecord(v.collateralId, v.asset, v.executor, v.offered);
        if (ISettlementPool7540(pool).settlementPending()) revert ResidualMismatch();
        if (
            msg.sender != sources[pool]
                && !IAccessControl(address(this)).hasRole(Roles.HOTSWAP_ROLE, msg.sender)
        ) {
            revert IAccessControl.AccessControlUnauthorizedAccount(msg.sender, Roles.HOTSWAP_ROLE);
        }
        // Pending solver custody (lots and cycles at sellers) is still an obligation, but is not held here.
        if (
            v.externalCollateral > v.lotCollateral + v.held
                || IERC20(token).balanceOf(address(this))
                    < v.held + v.lotCollateral - v.externalCollateral
        ) {
            revert ResidualMismatch();
        }
        (sold, received) = _sellThrough(token, v.asset, v.executor, v.offered, floor, data);
        _checkFill(sold, received, floor, 10 ** decimals);
        if (sold == 0) return (0, 0, 0, address(0), pool);
        reserve = registry.validateDeposit(v.asset);
        bytes32 expectedState = registry.depositState(v.asset, received);
        uint256 expected = received * (10 ** (18 - IRecoveryReserve(reserve).backingDecimals()));
        IERC20(v.asset).forceApprove(reserve, received);
        minted = IRecoveryReserve(reserve).depositFromTreasury(received);
        IERC20(v.asset).forceApprove(reserve, 0);
        if (minted != expected || registry.depositState(v.asset, 0) != expectedState) {
            revert ResidualMismatch();
        }
    }

    struct ArbLeg {
        address reserveRegistry;
        address prusd;
        address greaterMarket;
        uint256 cid;
        address buyer;
        uint256 spend;
        address asset;
        address executor;
        uint16 gapBps;
        uint16 minProfitBps;
    }

    struct ArbReceipt {
        address token;
        uint8 decimals;
        uint256 floor;
        uint256 ceiling;
        uint256 tokenBefore;
        uint256 prusdBefore;
        uint256 claimedSpent;
        uint256 returned;
        uint256 claimedBought;
    }

    error ArbitrageUnprofitable();

    /// @notice Step 1 entry (runs in the Treasury's context): resolve the pool and its arbitrage route from the pool
    ///         registry, cap the spend at the Treasury's free PRUSD and the route's maximum, then run the round trip.
    ///         Returns the pool id with the measured spend and mint.
    function arbitrage(
        uint256 cid,
        uint256 spend,
        address asset,
        address executor,
        bytes calldata data
    ) external returns (uint256 pid, uint256 spent, uint256 minted) {
        return _budgetedArbitrage(
            cid,
            Math.min(spend, ITreasuryArbView(address(this)).spendableCash()),
            asset,
            executor,
            data
        );
    }

    /// @dev Only the Treasury's self-only callback may supply a reserved allocation as its budget.
    function cycleArbitrage(
        uint256 cid,
        uint256 budget,
        address asset,
        address executor,
        bytes calldata data
    ) external returns (uint256 spent, uint256 minted) {
        (, spent, minted) = _budgetedArbitrage(cid, budget, asset, executor, data);
    }

    function _budgetedArbitrage(
        uint256 cid,
        uint256 spend,
        address asset,
        address executor,
        bytes calldata data
    ) private returns (uint256 pid, uint256 spent, uint256 minted) {
        ITreasuryArbView t = ITreasuryArbView(address(this));
        address poolRegistry = t.poolRegistry();
        pid = IStabilityPoolRegistry(poolRegistry).poolForCollateral(cid);
        (address buyer, uint256 maxSpend, uint16 gapBps, uint16 minProfitBps) =
            IArbRoutes(poolRegistry).arbRoute(pid);
        if (pid == 0 || buyer == address(0)) revert ResidualMismatch();
        spend = Math.min(spend, maxSpend);
        if (spend == 0) return (pid, 0, 0);
        (spent,, minted) = _arbitrage(
            ArbLeg(
                t.reserveRegistry(),
                t.prusd(),
                t.greaterMarket(),
                cid,
                buyer,
                spend,
                asset,
                executor,
                gapBps,
                minProfitBps
            ),
            data
        );
    }

    /// @notice Buy the collateral on the pool's sale venue at or below `ceiling = market × (1 − gap)`, sell ALL of it
    ///         on the admitted recovery route at or above its floor, deposit the stablecoin into the reserve and mint
    ///         PRUSD 1:1; revert unless the mint beats the spend by the minimum profit. Every figure is a measured
    ///         balance delta; the venues' claims must match them. Runs in the Treasury's context (delegatecall).
    function _arbitrage(ArbLeg memory a, bytes calldata data)
        private
        returns (uint256 spent, uint256 bought, uint256 minted)
    {
        ArbReceipt memory r;
        PricingEvidence.Quote memory pricing;
        (r.token, r.decimals, r.floor, pricing) = ILotRouteCheck(a.reserveRegistry)
            .validateLotRouteWithPricing(a.cid, a.asset, a.executor);
        (uint256 g, bool valid) = IGreaterMarketReference(a.greaterMarket).greaterMarketPrice(a.cid);
        if (!valid || g == 0) revert ResidualMismatch();
        r.ceiling = Math.mulDiv(g, 10_000 - a.gapBps, 10_000);
        // Buy leg: hand the buyer exactly `spend`, measure what came back.
        r.tokenBefore = IERC20(r.token).balanceOf(address(this));
        r.prusdBefore = IERC20(a.prusd).balanceOf(address(this));
        uint256 buyerBefore = IERC20(a.prusd).balanceOf(a.buyer);
        IERC20(a.prusd).safeTransfer(a.buyer, a.spend);
        if (IERC20(a.prusd).balanceOf(a.buyer) != buyerBefore + a.spend) revert ResidualMismatch();
        (r.claimedSpent, r.returned, r.claimedBought) =
            IArbBuyer(a.buyer).buyAtCeiling(r.token, a.spend, r.ceiling, data);
        spent = r.prusdBefore - IERC20(a.prusd).balanceOf(address(this));
        bought = IERC20(r.token).balanceOf(address(this)) - r.tokenBefore;
        if (
            spent > a.spend || r.claimedSpent != spent || r.returned != a.spend - spent
                || r.claimedBought != bought
        ) revert ResidualMismatch();
        if (bought == 0) {
            if (spent != 0) revert ResidualMismatch();
            return (0, 0, 0);
        }
        if (spent == 0) revert ResidualMismatch(); // collateral for nothing: a misbehaving buyer, not a trade
        // The average price paid never exceeds the ceiling.
        if (spent > Math.mulDiv(bought, r.ceiling, 10 ** r.decimals)) revert ResidualMismatch();
        // Sell leg: all of it, at or above the floor, then deposit and mint as a recovery sale does.
        PricingEvidence.record(a.executor, r.token, a.asset, r.floor, bought, pricing);
        (uint256 sold, uint256 received) =
            _sellThrough(r.token, a.asset, a.executor, bought, r.floor, data);
        if (sold != bought) revert ResidualMismatch();
        _checkFill(sold, received, r.floor, 10 ** r.decimals);
        minted = _depositAndMint(a.reserveRegistry, a.asset, received);
        if (minted < spent + Math.mulDiv(spent, a.minProfitBps, 10_000, Math.Rounding.Ceil)) {
            revert ArbitrageUnprofitable();
        }
        // Reject unexpected PRUSD inside the optional attempt's rollback boundary.
        if (IERC20(a.prusd).balanceOf(address(this)) != r.prusdBefore + minted - spent) {
            revert ResidualMismatch();
        }
    }

    /// @dev Deposit a measured stablecoin receipt into its reserve and mint PRUSD 1:1 (shared by the recovery sale).
    function _depositAndMint(address reserveRegistry, address asset, uint256 received)
        private
        returns (uint256 minted)
    {
        IRecoveryReserves registry = IRecoveryReserves(reserveRegistry);
        address reserve = registry.validateDeposit(asset);
        bytes32 expectedState = registry.depositState(asset, received);
        uint256 expected = received * (10 ** (18 - IRecoveryReserve(reserve).backingDecimals()));
        IERC20(asset).forceApprove(reserve, received);
        minted = IRecoveryReserve(reserve).depositFromTreasury(received);
        IERC20(asset).forceApprove(reserve, 0);
        if (minted != expected || registry.depositState(asset, 0) != expectedState) {
            revert ResidualMismatch();
        }
    }

    /// @notice The warehouse settlement-source check (moved here unchanged for EIP-170): the source must be the
    ///         canonical warehouse for the pool's collateral and bound back to this pool and Treasury.
    function checkSettlementSource(address vault, address pool, address source) external view {
        IWarehouseCycleSource w = IWarehouseCycleSource(source);
        uint256 cid = ISettlementPool7540(pool).collateralId();
        if (
            source != WarehouseSourceAuth.canonicalFromVault(vault, cid)
                || !IERC165(source).supportsInterface(type(IWarehouseCycleSource).interfaceId)
                || w.pool() != pool || w.treasury() != address(this) || w.collateralId() != cid
        ) revert SettlementSourceInvalid();
    }

    /// @notice Pull a bite's unsold residual from the warehouse and price it at the stop price (moved here unchanged
    ///         for EIP-170). The receipt is measured, never trusted.
    function receiveResidual(
        ICollateralRegistry collateralRegistry,
        address source,
        uint256 cid,
        uint256 amount,
        uint256 stop
    ) external returns (uint256 consideration) {
        if (address(collateralRegistry) == address(0)) {
            revert CollateralRegistryNotSet();
        }
        CollateralConfig memory c = collateralRegistry.getCollateral(cid);
        if (
            c.token.code.length == 0 || c.token != IResidualSource(source).collateralToken()
                || c.decimals != IResidualSource(source).collateralDecimals()
        ) revert ResidualMismatch();
        consideration = Math.mulDiv(amount, stop, 10 ** c.decimals, Math.Rounding.Ceil);
        IERC20 token = IERC20(c.token);
        uint256 beforeBalance = token.balanceOf(address(this));
        token.safeTransferFrom(source, address(this), amount);
        if (token.balanceOf(address(this)) != beforeBalance + amount) revert ResidualMismatch();
    }

    // ------------------------------------------------------------ task 0191: opening lots at fold (moved, DEF-280)

    event LotOpened(
        bytes32 indexed lotId,
        uint256 indexed collateralId,
        uint256 indexed poolId,
        uint256 collateral,
        uint256 principal,
        uint256 interest,
        uint256 facilityId
    );
    event LotMarked(bytes32 indexed lotId, uint256 markedShortfall, uint256 price);

    event AggregateLotOpened(
        bytes32 indexed lotId,
        address indexed warehouse,
        uint256 indexed liquidationCycleId,
        uint256 carriedCollateral
    );
    event LotFacilityAssigned(
        bytes32 indexed lotId, uint256 indexed facilityId, uint256 principal, uint256 interest
    );
    event LotFacilityDebtRetired(
        bytes32 indexed lotId, uint256 indexed facilityId, uint256 principal, uint256 interest
    );
    event LotPrincipalRetired(bytes32 indexed lotId, uint256 indexed facilityId, uint256 principal);

    /// @notice Pull one aggregate fold and reclassify only its own cycle's unsold bite holdings.
    ///         This is Treasury storage and custody, not a second asset ledger or a new authority.
    function openAggregateLot(
        mapping(bytes32 => Lot) storage lots,
        FoldLedger storage ledger,
        mapping(bytes32 => uint256) storage lotMarkedShortfall,
        CycleLedger storage cycles,
        mapping(uint256 => uint256) storage seizedInventory,
        mapping(uint256 => uint256) storage lotCollateral,
        mapping(uint256 => uint256) storage foldedDebt,
        FoldContext memory context,
        LotHandover[] calldata handover
    ) external returns (uint256 received) {
        uint256 cid = context.collateralId;
        uint256 pid = context.poolId;
        if (
            handover.length == 0 || pid == 0
                || msg.sender != WarehouseSourceAuth.canonicalFromVault(context.vault, cid)
        ) revert ResidualMismatch();
        ILiquidationCycleSource source = ILiquidationCycleSource(msg.sender);
        uint256 cycle = source.liquidationCycleId();
        if (cycle == 0 || !source.liquidationCycleOpen()) revert ResidualMismatch();
        bytes32 id = keccak256(abi.encode(msg.sender, cycle));
        if (lots[id].poolId != 0) revert ResidualMismatch();
        IERC20 token = IERC20(context.collateralRegistry.getCollateral(cid).token);
        uint256 beforeBalance = token.balanceOf(address(this));
        received = token.balanceOf(msg.sender);
        token.safeTransferFrom(msg.sender, address(this), received);
        if (token.balanceOf(address(this)) != beforeBalance + received) revert ResidualMismatch();

        uint256 principal;
        uint256 interest;
        for (uint256 k; k < handover.length; ++k) {
            LotHandover calldata h = handover[k];
            FacilityBalance storage f = ledger.debt[id][h.facilityId];
            if (h.facilityId == 0 || f.assigned) revert ResidualMismatch();
            f.assigned = true;
            // Empty historical facility rows do not grow the executable lot's allocation list.
            if (h.principal == 0 && h.interest == 0) continue;
            f.principal = h.principal;
            f.interest = h.interest;
            ledger.facilities[id].push(h.facilityId);
            principal += h.principal;
            interest += h.interest;
            emit LotFacilityAssigned(id, h.facilityId, h.principal, h.interest);
        }
        if (principal + interest == 0 || received == 0) revert ResidualMismatch();
        uint256 carried = cycles.collateral[pid][cycle];
        if (carried != 0) {
            if (cycles.active[pid] != cycle) revert ResidualMismatch();
            seizedInventory[cid] -= carried;
            delete cycles.collateral[pid][cycle];
            cycles.held[pid].remove(cycle);
        }
        uint256 collateral = received + carried;
        lotCollateral[cid] += collateral;
        if (
            context.externalCollateral > lotCollateral[cid]
                || token.balanceOf(address(this))
                    < seizedInventory[cid] + lotCollateral[cid] - context.externalCollateral
        ) {
            revert ResidualMismatch();
        }
        foldedDebt[cid] += principal + interest;
        lots[id] = Lot(pid, cid, collateral, principal, interest);
        emit LotOpened(id, cid, pid, collateral, principal, interest, 0);
        emit AggregateLotOpened(id, msg.sender, cycle, carried);
        (uint256 marked, uint256 price) = markShortfall(
            context.greaterMarket, context.collateralRegistry, cid, collateral, principal, interest
        );
        lotMarkedShortfall[id] = marked;
        emit LotMarked(id, marked, price);
    }
}

src/registries/PsmAssetRegistry.sol

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

import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {Roles} from "../libraries/Roles.sol";

interface IERC20Decimals {
    function decimals() external view returns (uint8);
}

/// @notice Permanent asset configuration for SRV admission. Each SRV owns its backing/debt accounting.
///         Risk admins control new issuance and exit eligibility, not holder redemption or registration deletion.
struct PsmAsset {
    bool enabled; // registered
    bool mintPaused; // pause NEW issuance without trapping redeemers
    bool escapeEnabled; // usable as a Treasury exit asset; independent of mint pause
    bool testOnly; // e.g. fUSD — refused by a production registry
    uint8 decimals; // <= 18, frozen at admission — the normalization basis
    address oracle; // price feed (1e18 = $1); mint reverts if depegged beyond maxDepegBps
    uint256 maxDepegBps; // max oracle deviation from $1 tolerated for NEW mints
}

contract PsmAssetRegistry is AccessControl {
    /// @notice A production registry refuses `testOnly` assets (e.g. fUSD). Testnet deploys pass `false`.
    bool public immutable production;

    mapping(address token => PsmAsset) private _assets;
    address[] private _assetList;

    error ZeroAddress();
    error UnknownAsset(address token);
    error AlreadyListed(address token);
    error UnsupportedDecimals(uint8 decimals);
    error TestAssetInProduction(address token);

    event AssetAdded(
        address indexed token, address oracle, uint256 maxDepegBps, bool testOnly, uint8 decimals
    );
    event MaxDepegSet(address indexed token, uint256 maxDepegBps);
    event MintPausedSet(address indexed token, bool paused);
    event EscapeEnabledSet(address indexed token, bool enabled);

    constructor(address admin, bool production_) {
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        production = production_;
    }

    // ── Governance (RISK_ADMIN) ──

    /// @notice Admit a stablecoin. `decimals` (≤18) is read once + frozen — the normalization basis, which must
    ///         never change for an admitted asset. A production registry refuses `testOnly` assets.
    function addAsset(address token, address oracle, uint256 maxDepegBps, bool testOnly)
        external
        onlyRole(Roles.RISK_ADMIN_ROLE)
    {
        if (token == address(0) || oracle == address(0)) revert ZeroAddress();
        if (_assets[token].enabled) revert AlreadyListed(token);
        if (production && testOnly) revert TestAssetInProduction(token);
        uint8 dec = IERC20Decimals(token).decimals();
        if (dec > 18) revert UnsupportedDecimals(dec);
        _assets[token] = PsmAsset({
            enabled: true,
            mintPaused: false,
            escapeEnabled: false, // governance flags escape-eligibility explicitly (0071)
            testOnly: testOnly,
            decimals: dec,
            oracle: oracle,
            maxDepegBps: maxDepegBps
        });
        _assetList.push(token);
        emit AssetAdded(token, oracle, maxDepegBps, testOnly, dec);
    }

    function setMaxDepegBps(address token, uint256 maxDepegBps)
        external
        onlyRole(Roles.RISK_ADMIN_ROLE)
    {
        _requireListed(token);
        _assets[token].maxDepegBps = maxDepegBps;
        emit MaxDepegSet(token, maxDepegBps);
    }

    function setMintPaused(address token, bool paused) external onlyRole(Roles.RISK_ADMIN_ROLE) {
        _requireListed(token);
        _assets[token].mintPaused = paused;
        emit MintPausedSet(token, paused);
    }

    /// @notice 0071: flag/unflag a stable as usable for the Treasury hotswap "escape" (best-of-N offload venue).
    ///         DISTINCT from `mintPaused` — a stable can be redeemable but not an escape venue, or an
    ///         escape venue with mint paused. Execution-time depeg gating is separate (the asset's oracle +
    ///         `maxDepegBps`), not this flag.
    function setEscapeEnabled(address token, bool enabled)
        external
        onlyRole(Roles.RISK_ADMIN_ROLE)
    {
        _requireListed(token);
        _assets[token].escapeEnabled = enabled;
        emit EscapeEnabledSet(token, enabled);
    }

    // ── Views ──

    function getAsset(address token) external view returns (PsmAsset memory) {
        return _assets[token];
    }

    /// @notice 0071: usable as a hotswap escape asset — registered AND governance-flagged escape-eligible. The
    ///         execution-time depeg check (oracle within `maxDepegBps`) is applied separately by the Treasury.
    function isEscapeEnabled(address token) external view returns (bool) {
        PsmAsset storage a = _assets[token];
        return a.enabled && a.escapeEnabled;
    }

    function isEnabled(address token) external view returns (bool) {
        return _assets[token].enabled;
    }

    function assetCount() external view returns (uint256) {
        return _assetList.length;
    }

    function assetAt(uint256 i) external view returns (address) {
        return _assetList[i];
    }

    function _requireListed(address token) private view {
        if (!_assets[token].enabled) revert UnknownAsset(token);
    }
}

src/registries/StableReserveRegistry.sol

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

import {PricingEvidence, ISalePricingEvents} from "../libraries/SalePricing.sol";

import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {StableReserveVault, IReserveTreasuryIdentity} from "../StableReserveVault.sol";
import {PsmAssetRegistry, PsmAsset} from "./PsmAssetRegistry.sol";
import {IOracleAdapter} from "../interfaces/IOracleAdapter.sol";
import {IPRUSD} from "../interfaces/IPRUSD.sol";
import {Roles} from "../libraries/Roles.sol";
import {Treasury} from "../Treasury.sol";
import {ISettlementPool7540} from "../interfaces/ISettlementPool7540.sol";
import {CollateralConfig} from "../types/ProtocolTypes.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {StableReserveMath} from "../libraries/StableReserveMath.sol";

interface IRecoveryExecutorIdentity {
    function pool() external view returns (address);
    function collateral() external view returns (address);
    function prusd() external view returns (address);
}

/// @notice Fixed-code reserves, one per admitted backing asset. Never holds inventory or funds.
contract StableReserveRegistry is AccessControl, ISalePricingEvents {
    address public immutable treasury;
    IPRUSD public immutable prusd;
    PsmAssetRegistry public immutable assetRegistry;
    mapping(address => address) public reserveForAsset;
    address[] private _assets;

    struct RecoveryRoute {
        address asset;
        address executor;
        bool enabled;
    }
    mapping(uint256 => RecoveryRoute[]) private _routes;
    mapping(uint256 => mapping(address => uint256)) private _routeIndex;

    error InvalidReserveBinding();
    error ReserveExists();
    error ReserveIssuanceUnavailable();
    event ReserveCreated(address indexed asset, address indexed reserve, address indexed treasury);
    event RecoveryRouteSet(
        uint256 indexed collateralId, address indexed asset, address indexed executor, bool enabled
    );

    constructor(address admin, address treasury_, address assets_) {
        if (admin == address(0) || treasury_.code.length == 0 || assets_.code.length == 0) {
            revert InvalidReserveBinding();
        }
        treasury = treasury_;
        prusd = IPRUSD(IReserveTreasuryIdentity(treasury_).prusd());
        if (address(prusd).code.length == 0) revert InvalidReserveBinding();
        assetRegistry = PsmAssetRegistry(assets_);
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        _grantRole(Roles.REGISTRY_ADMIN_ROLE, admin);
    }

    function createReserve(address asset)
        external
        onlyRole(Roles.REGISTRY_ADMIN_ROLE)
        returns (address reserve)
    {
        if (reserveForAsset[asset] != address(0)) {
            revert ReserveExists();
        }
        PsmAsset memory a = assetRegistry.getAsset(asset);
        if (
            !a.enabled || asset == address(prusd) || asset.code.length == 0 || a.decimals > 18
                || IERC20Metadata(asset).decimals() != a.decimals
        ) revert InvalidReserveBinding();
        reserve = address(new StableReserveVault(IERC20(asset), prusd, treasury));
        reserveForAsset[asset] = reserve;
        _assets.push(asset);
        emit ReserveCreated(asset, reserve, treasury);
    }

    /// @notice Admission and mint controls, never a quote for collateral execution. SRVs have no holding cap.
    function validateDeposit(address asset) public view returns (address reserve) {
        (reserve,,) = _admitted(asset);
    }

    function _admitted(address asset)
        private
        view
        returns (address reserve, uint8 decimals, uint256 p)
    {
        reserve = reserveForAsset[asset];
        PsmAsset memory a = assetRegistry.getAsset(asset);
        if (
            reserve == address(0) || !a.enabled || !a.escapeEnabled || a.mintPaused
                || a.decimals != StableReserveVault(reserve).backingDecimals()
                || IERC20Metadata(asset).decimals() != a.decimals
        ) {
            revert ReserveIssuanceUnavailable();
        }
        decimals = a.decimals;
        p = IOracleAdapter(a.oracle).price();
        uint256 delta = p > 1e18 ? p - 1e18 : 1e18 - p;
        if (p == 0 || a.maxDepegBps > 10_000 || delta > a.maxDepegBps * 1e14) {
            revert ReserveIssuanceUnavailable();
        }
    }

    /// @notice Read-only admission. Custody and every inventory/TAB mutation remain in Treasury.
    function validateRecovery(uint256 cid, address asset, address executor)
        external
        view
        returns (address token, address pool, uint8 decimals, uint256 floor)
    {
        (token, pool, decimals, floor,) = _validateRecovery(cid, asset, executor);
    }

    function validateRecoveryAndRecord(
        uint256 cid,
        address asset,
        address executor,
        uint256 offered
    ) external returns (address token, address pool, uint8 decimals, uint256 floor) {
        if (msg.sender != treasury) revert InvalidReserveBinding();
        PricingEvidence.Quote memory q;
        (token, pool, decimals, floor, q) = _validateRecovery(cid, asset, executor);
        PricingEvidence.record(executor, token, asset, floor, offered, q);
    }

    function _validateRecovery(uint256 cid, address asset, address executor)
        private
        view
        returns (
            address token,
            address pool,
            uint8 decimals,
            uint256 floor,
            PricingEvidence.Quote memory q
        )
    {
        Treasury t = Treasury(treasury);
        uint256 routeIndex = _routeIndex[cid][executor];
        if (
            routeIndex == 0 || !_routes[cid][routeIndex - 1].enabled
                || _routes[cid][routeIndex - 1].asset != asset
        ) revert InvalidReserveBinding();
        uint256 pid = t.inventoryPoolId(cid);
        pool = t.poolRegistry().getPool(pid).pool;
        ISettlementPool7540 p = ISettlementPool7540(pool);
        CollateralConfig memory c = t.collateralRegistry().getCollateral(cid);
        if (
            pid == 0 || t.poolRegistry().poolIdForPool(pool) != pid || p.collateralId() != cid
                || p.settlementLedger() != treasury || p.asset() != address(prusd)
                || p.settlementPending() || !t.allowedHotswapExecutor(executor) || c.decimals > 18
                || c.token == asset || asset == address(prusd)
                || IRecoveryExecutorIdentity(executor).pool() != treasury
                || IRecoveryExecutorIdentity(executor).collateral() != c.token
                || IRecoveryExecutorIdentity(executor).prusd() != asset
        ) revert InvalidReserveBinding();
        token = c.token;
        decimals = c.decimals;
        (floor, q) = _recoveryPricing(cid, asset);
    }

    /// @notice Waterfall repair quote (task 0197): the asset's reserve, its gap (debt above backing, PRUSD units) and
    ///         its effective rate (Tim's guide §2: min(1, backing / debt) times the stablecoin's price). The waterfall
    ///         repairs the highest effective rate first, so a depegged stablecoin's reserve waits. Zero reserve when
    ///         the asset has none.
    function repairQuote(address asset)
        external
        view
        returns (address reserve, uint256 gap, uint256 effectiveRate)
    {
        reserve = reserveForAsset[asset];
        if (reserve == address(0)) return (address(0), 0, 0);
        StableReserveVault r = StableReserveVault(reserve);
        gap = r.repairGap();
        uint256 debt = r.debt();
        uint256 backed = StableReserveMath.normalize(r.backing(), r.backingDecimals());
        uint256 nominal = debt == 0 || backed >= debt ? 1e18 : Math.mulDiv(backed, 1e18, debt);
        PsmAsset memory a = assetRegistry.getAsset(asset);
        effectiveRate = Math.mulDiv(nominal, IOracleAdapter(a.oracle).price(), 1e18);
    }

    /// @notice Read-only admission for an SRV fold of Treasury lot collateral (task 0192). Same route, executor
    ///         binding, depeg gate and floor as `validateRecovery`, without the unwind-inventory binding: lots are
    ///         held apart from unwind inventory and carry their own originating pool.
    function validateLotRoute(uint256 cid, address asset, address executor)
        external
        view
        returns (address token, uint8 decimals, uint256 floor)
    {
        (token, decimals, floor,) = validateLotRouteWithPricing(cid, asset, executor);
    }

    function validateLotRouteWithPricing(uint256 cid, address asset, address executor)
        public
        view
        returns (address token, uint8 decimals, uint256 floor, PricingEvidence.Quote memory q)
    {
        Treasury t = Treasury(treasury);
        uint256 routeIndex = _routeIndex[cid][executor];
        CollateralConfig memory c = t.collateralRegistry().getCollateral(cid);
        if (
            routeIndex == 0 || !_routes[cid][routeIndex - 1].enabled
                || _routes[cid][routeIndex - 1].asset != asset
                || !t.allowedHotswapExecutor(executor) || c.decimals > 18 || c.token == asset
                || asset == address(prusd) || IRecoveryExecutorIdentity(executor).pool() != treasury
                || IRecoveryExecutorIdentity(executor).collateral() != c.token
                || IRecoveryExecutorIdentity(executor).prusd() != asset
        ) revert InvalidReserveBinding();
        token = c.token;
        decimals = c.decimals;
        (floor, q) = _recoveryPricing(cid, asset);
    }

    /// @dev O4 oracle-bound minimum in raw backing units per whole collateral, not a fill quote.
    function recoveryFloor(uint256 cid, address asset) public view returns (uint256 floor) {
        (floor,) = _recoveryPricing(cid, asset);
    }

    function _recoveryPricing(uint256 cid, address asset)
        private
        view
        returns (uint256 floor, PricingEvidence.Quote memory q)
    {
        (, uint8 decimals, uint256 price) = _admitted(asset);
        Treasury t = Treasury(treasury);
        uint256 tolerance = t.hotswapSlippageBps();
        (uint256 g, bool valid) = t.greaterMarket().greaterMarketPrice(cid);
        if (tolerance == 0 || tolerance > 10_000 || !valid || g == 0) {
            revert ReserveIssuanceUnavailable();
        }
        uint256 usdFloor = Math.mulDiv(g, 10_000 - tolerance, 10_000, Math.Rounding.Ceil);
        floor = Math.mulDiv(usdFloor, 10 ** decimals, price, Math.Rounding.Ceil);
        if (floor == 0) revert ReserveIssuanceUnavailable();
        q = PricingEvidence.Quote(g, price, tolerance, 0);
    }

    function assetCount() external view returns (uint256) {
        return _assets.length;
    }

    function assetAt(uint256 i) external view returns (address) {
        return _assets[i];
    }

    /// @notice Discoverable routes use the Treasury's existing risk authority and executor allowlist.
    function setRecoveryRoute(uint256 cid, address asset, address executor, bool enabled) external {
        Treasury t = Treasury(treasury);
        if (!t.hasRole(Roles.RISK_ADMIN_ROLE, msg.sender)) revert InvalidReserveBinding();
        uint256 index = _routeIndex[cid][executor];
        if (enabled) {
            address token = t.collateralRegistry().getCollateral(cid).token;
            if (
                reserveForAsset[asset] == address(0) || !t.allowedHotswapExecutor(executor)
                    || IRecoveryExecutorIdentity(executor).pool() != treasury
                    || IRecoveryExecutorIdentity(executor).collateral() != token
                    || IRecoveryExecutorIdentity(executor).prusd() != asset
            ) revert InvalidReserveBinding();
        }
        if (index == 0) {
            if (!enabled) revert InvalidReserveBinding();
            _routes[cid].push(RecoveryRoute(asset, executor, enabled));
            _routeIndex[cid][executor] = _routes[cid].length;
        } else {
            RecoveryRoute storage route = _routes[cid][index - 1];
            if (route.asset != asset) revert InvalidReserveBinding();
            route.enabled = enabled;
        }
        emit RecoveryRouteSet(cid, asset, executor, enabled);
    }

    function routeCount(uint256 cid) external view returns (uint256) {
        return _routes[cid].length;
    }

    function routeAt(uint256 cid, uint256 index)
        external
        view
        returns (address asset, address executor, bool enabled)
    {
        RecoveryRoute memory r = _routes[cid][index];
        return (r.asset, r.executor, r.enabled);
    }

    /// @notice Exact reserve/custody snapshot, optionally advanced by one nominal deposit.
    /// @dev Treasury compares the expected pre-deposit commitment with the actual post-deposit one.
    ///      This is read-only factoring for EIP-170, not an accounting writer or an executor.
    function depositState(address asset, uint256 incoming) external view returns (bytes32) {
        StableReserveVault reserve = StableReserveVault(reserveForAsset[asset]);
        uint256 mint = incoming * (10 ** (18 - reserve.backingDecimals()));
        return keccak256(
            abi.encode(
                reserve.debt() + mint,
                reserve.backing() + incoming,
                prusd.balanceOf(treasury) + mint,
                prusd.totalSupply() + mint,
                IERC20(asset).balanceOf(treasury) - incoming
            )
        );
    }
}

src/types/LotTypes.sol

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

/// @notice A Treasury lot: the collateral and obligation of one folded liquidation cycle, held by
///         the Treasury until it is sold on V4, folded through a reserve, or filled on the tender book (0215).
struct Lot {
    uint256 poolId;
    uint256 collateralId;
    uint256 collateral;
    uint256 principal;
    uint256 interest;
}

/// @notice One facility's frozen debt within an aggregate fold lot. Borrower attribution is event-derived.
struct LotHandover {
    uint256 facilityId;
    uint256 principal;
    uint256 interest;
}

src/types/ProtocolTypes.sol

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

/// @notice Shared enums and config/state structs for the facility-first CDP protocol.
/// @dev Types only — no logic, no storage. Registries, vault, pools, and subgraph type-generation
///      all reference this one source so `Collateral != Facility != Stability Pool` stays explicit.

/// @notice Canonical facility lifecycle states. Transition rules live in `FacilityStatusLib`.
enum FacilityStatus {
    Active,
    Paused,
    RepayOnly,
    Deprecated
}

/// @notice Stability pool exposure model.
enum PoolExposure {
    SingleAsset,
    MultiAsset
}

/// @notice Collateral asset definition. Pricing resolves separately through canonical G by `collateralId`.
struct CollateralConfig {
    uint256 collateralId;
    address token;
    uint8 decimals;
    uint256 oracleStalenessThreshold; // reserved — TODO-ORACLE-001
    uint256 twapWindow; // reserved — TODO-ORACLE-001
    uint256 maxDeviationBps; // reserved — TODO-ORACLE-001
    bool enabled;
}

/// @notice Immutable borrow-product terms. `termsHash` is registry-computed, never caller input.
struct FacilityConfig {
    uint256 facilityId;
    uint256 collateralId;
    address debtAsset;
    uint256 minOpeningCR; // Facility 1: 125% (canonical; 150% is legacy)
    uint256 liquidationCR; // Facility 1: 120%
    uint256 closeFactorBps; // Facility 1: 5000 (50%)
    uint256 liquidationBonusBps; // engine-bound; Facility 1: 1000 (10%)
    uint256 minInitialMint; // opening floor (MIN_MINT); launch facility 1,000 PRUSD
    uint256 minDebtAfterPartial; // floor left after a partial repay/liquidation (Proposed 500)
    uint256 maxDebtPerVault;
    uint256 globalDebtCap;
    uint256 mintFeeBps;
    uint256 aprBps; // fixed at registration; accrual reads this immutable facility term
    uint256 tokenOffsetCapBps; // PRYA offset cap (0046); disabled at launch
    bool redrawable; // may a borrower draw again after their first draw? (register REDRAW_LAUNCH)
    uint256 liquidationPoolId; // the ONE pool this facility routes liquidations to
    address liquidationEngine;
    address feeRecipient;
    address interestRecipient;
    address treasury;
    uint256 targetCR; // immutable warehouse target T in bps; current close-factor liquidation does not consume it
    bytes32 termsHash;
    bool nonReplenishing; // immutable capacity option; economics implemented separately
    uint256 drawExpiry; // immutable draw deadline; zero means no expiry
}

/// @notice Mutable facility accounting.
struct FacilityState {
    FacilityStatus status;
    uint256 currentPrincipalMinted;
    uint256 currentDebtOutstanding;
    uint256 lastAccruedAt;
}

/// @notice Borrower position, keyed by (borrower, facilityId). Never an NFT.
struct VaultData {
    uint256 collateralAmount;
    uint256 principalDebt; // raw PRUSD principal owed (== minted, still outstanding); supply == Σ principalDebt
    uint256 accruedInterest; // owed interest, NEVER minted; routed to interestRecipient on repay/close
    uint256 lastAccruedAt; // timestamp interest was last accrued (0 / unused when the facility has no interest)
    uint256 openedAt;
    bool exists;
}

/// @notice Stability pool metadata + routing. A collateralId is watched by at most one active pool.
struct StabilityPoolInfo {
    uint256 poolId;
    address pool;
    PoolExposure exposure;
    bool active;
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {
    "src/libraries/TreasuryCow.sol": {
      "TreasuryCow": "0xfDFD4dF6B52aa53e2BbCB7eB351dD4f2a54b8c0f"
    },
    "src/libraries/TreasuryFold.sol": {
      "TreasuryFold": "0x167E910A5A7244d5FfbcE874faC6bc1060453043"
    },
    "src/libraries/TreasurySales.sol": {
      "TreasurySales": "0x1780fB5873F0692108B06D14Ab5df853C1949d2a"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "lib/openzeppelin-community-contracts/contracts/:@openzeppelin/contracts/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/",
    "lib/openzeppelin-community-contracts/contracts/:@openzeppelin/contracts/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "forge-std/=lib/forge-std/src/",
    "@openzeppelin/community-contracts/=lib/openzeppelin-community-contracts/contracts/",
    "@openzeppelin7540/contracts/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/",
    "composable-cow/=lib/composable-cow/src/",
    "lib/composable-cow/:@openzeppelin/=lib/composable-cow/lib/@openzeppelin/",
    "lib/composable-cow/:@openzeppelin/=lib/composable-cow/lib/@openzeppelin/",
    "cowprotocol/=lib/composable-cow/lib/cowprotocol/src/",
    "safe/=lib/composable-cow/lib/safe/contracts/",
    "lib/composable-cow/lib/@openzeppelin/lib/forge-std/:ds-test/=lib/composable-cow/lib/@openzeppelin/lib/forge-std/lib/ds-test/src/",
    "lib/composable-cow/lib/@openzeppelin/lib/forge-std/:ds-test/=lib/composable-cow/lib/@openzeppelin/lib/forge-std/lib/ds-test/src/",
    "lib/composable-cow/lib/murky/lib/forge-std/:ds-test/=lib/composable-cow/lib/murky/lib/forge-std/lib/ds-test/src/",
    "lib/composable-cow/lib/murky/lib/forge-std/:ds-test/=lib/composable-cow/lib/murky/lib/forge-std/lib/ds-test/src/",
    "lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/openzeppelin-community-contracts/lib/wormhole-solidity-sdk/lib/forge-std/:ds-test/=lib/openzeppelin-community-contracts/lib/wormhole-solidity-sdk/lib/forge-std/lib/ds-test/src/",
    "lib/openzeppelin-community-contracts/lib/wormhole-solidity-sdk/lib/forge-std/:ds-test/=lib/openzeppelin-community-contracts/lib/wormhole-solidity-sdk/lib/forge-std/lib/ds-test/src/",
    "lib/composable-cow/lib/@openzeppelin/:erc4626-tests/=lib/composable-cow/lib/@openzeppelin/lib/erc4626-tests/",
    "lib/composable-cow/lib/@openzeppelin/:erc4626-tests/=lib/composable-cow/lib/@openzeppelin/lib/erc4626-tests/",
    "lib/composable-cow/lib/forge-std/:ds-test/=lib/composable-cow/lib/forge-std/lib/ds-test/src/",
    "lib/composable-cow/lib/forge-std/:ds-test/=lib/composable-cow/lib/forge-std/lib/ds-test/src/",
    "lib/composable-cow/lib/murky/:openzeppelin-contracts/=lib/composable-cow/lib/murky/lib/openzeppelin-contracts/",
    "lib/composable-cow/lib/murky/:openzeppelin-contracts/=lib/composable-cow/lib/murky/lib/openzeppelin-contracts/",
    "lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/:openzeppelin-contracts/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
    "lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/:openzeppelin-contracts/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
    "lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "@axelar-network/axelar-gmp-sdk-solidity/=lib/openzeppelin-community-contracts/lib/axelar-gmp-sdk-solidity/",
    "@openzeppelin-contracts-upgradeable/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts-upgradeable/",
    "@openzeppelin-contracts/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/",
    "@openzeppelin/=lib/composable-cow/lib/@openzeppelin/",
    "@zk-email/contracts/=lib/openzeppelin-community-contracts/lib/zk-email-verify/packages/contracts/",
    "@zk-email/email-tx-builder/=lib/openzeppelin-community-contracts/lib/email-tx-builder/packages/contracts/",
    "IERC20/=lib/openzeppelin-community-contracts/lib/wormhole-solidity-sdk/src/interfaces/token/",
    "SafeERC20/=lib/openzeppelin-community-contracts/lib/wormhole-solidity-sdk/src/libraries/",
    "axelar-gmp-sdk-solidity/=lib/openzeppelin-community-contracts/lib/axelar-gmp-sdk-solidity/contracts/",
    "ds-test/=lib/composable-cow/lib/forge-std/lib/ds-test/src/",
    "email-tx-builder/=lib/openzeppelin-community-contracts/lib/email-tx-builder/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "murky/=lib/composable-cow/lib/murky/src/",
    "openzeppelin-community-contracts/=lib/openzeppelin-community-contracts/contracts/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin/=lib/composable-cow/lib/@openzeppelin/contracts/",
    "wormhole-sdk/=lib/openzeppelin-community-contracts/lib/wormhole-solidity-sdk/src/",
    "wormhole-solidity-sdk/=lib/openzeppelin-community-contracts/lib/wormhole-solidity-sdk/src/",
    "zk-email-verify/=lib/openzeppelin-community-contracts/lib/zk-email-verify/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.