Skip to content
Verified contractPartialMIT

ValinityLoanLens

Address0x080f02221b5799d9611911f48c892e4bc578d6bb
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.27

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.27+commit.40a35a09
Language
solidity
Optimization
Yes, 100 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,758,357
Creation transaction
0xb0d9bd29a8…983560bb25
Libraries
contracts/officer/ValinityLoanLens.sol:VLOLegacyLib0xb674…aede62

contracts/officer/ValinityLoanLens.sol

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

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {VLOLegacyLib, Loan, LegacyUnlock} from "./VLOLegacyLib.sol";

interface ILensVlo {
    function getLoan(address borrower, address asset) external view returns (Loan memory);
    function getVyLoan(address borrower, address asset) external view returns (Loan memory);
    function getLegacyPosition(address borrower, address asset)
        external view returns (Loan memory loan, LegacyUnlock[] memory tranches);
    /// @notice Existence of the NORMAL slot only — deliberately un-aggregated on the
    ///         officer, which is what makes it the right split key here.
    function isActive(address borrower, address asset) external view returns (bool);
    /// @notice Interest across BOTH books, each slot accrued against its own clock
    ///         and capped at its own collateral. The only correct total.
    function getAccruedInterest(address borrower, address asset) external view returns (uint256);
    /// @notice Asset that VY-loan borrowers deposited and are owed back. The asset
    ///         lane may not lend it out — the officer's reserve floor.
    function vyLoanCollateralPerAsset(address asset) external view returns (uint256);
    function getLTV(address asset) external view returns (uint256);
    function getTotalLoaned(address asset) external view returns (uint256);
    function getTotalCirculatingVY() external view returns (uint256);
    function interestRatePerSecond() external view returns (uint256);
    function processingFeePercentage() external view returns (uint16);
    function loanCapBps() external view returns (uint16);
    function marketLtvBps() external view returns (uint16);
    function supportedAsset(address asset) external view returns (bool);
    function priceSources() external view returns (address oracle, address assetTwap);
    function legacyConfig()
        external
        view
        returns (uint16 bps, uint32 lockPeriod, uint128 minVy, bool migrating, address sink, uint256 rows);
}

interface ILensVyOracle {
    function vyPerUsdcX112() external view returns (uint224);
}

interface ILensAssetTwap {
    function getAssetTwapPrice(address asset) external view returns (uint256);
}

interface ILensDax {
    function hasPool(address asset) external view returns (bool);
    function assetToPoolId(address asset) external view returns (uint256);
    function getPoolReserves(uint256 poolId)
        external view returns (address asset, uint256 reserveVY, uint256 reserveAsset);
}

/**
 * @title ValinityLoanLens
 * @notice Read-only companion to {ValinityLoanOfficer}. Holds the entire UI view
 *         surface, which the officer has no bytecode left to carry.
 *
 * @dev WHY THIS IS SEPARATE, not a convenience: VLO sits at 24,502 / 24,576 bytes.
 *      These eight views cost 2,381 bytes when they lived there — the single
 *      largest block of what pushed V11 over EIP-170. Keeping them out is what
 *      makes the officer deployable at all.
 *
 *      Being standalone and stateless, this contract is REDEPLOYABLE FREELY and
 *      carries no upgrade risk: nothing points at it on-chain, so replacing it is a
 *      frontend config change and nothing more.
 *
 *      Every figure here is derived from VLO's own public surface plus the two
 *      oracles it prices against, so a Lens read and the officer's behaviour cannot
 *      diverge. The legacy surcharge in particular calls {VLOLegacyLib-surchargeOf}
 *      — the exact function the repay path charges with, not a copy of it.
 */
contract ValinityLoanLens {
    uint8 internal constant DEFAULT_DECIMALS = 18;
    uint256 internal constant WAD = 1e18;
    uint16 internal constant BPS = 10_000;

    ILensVlo public immutable vlo;
    ILensDax public immutable dax;

    error InvalidAddress();
    error PaymentTooHigh();

    // ── Return shapes. Field order matches the structs these views had while they
    //    lived in VLO, so existing frontend decoders are unaffected. ────────────

    struct AssetView {
        uint256 ltv;            // asset units per VY, WAD-scaled
        uint256 reserveBalance; // V10: the asset leg of that asset's DAX pool
        uint256 totalLoaned;
    }

    struct LoanView {
        uint256 collateral;
        uint256 principal;
        uint64 openedAt;
        uint64 interestAppliedAt;
        uint256 ltv;
        uint256 accruedInterest;
        uint256 netCollateral;
        uint256 interestCarry;
    }

    struct LoanConstraintsView {
        uint256 maxCollateral;
        uint256 maxPrincipal;
    }

    struct NewLoanView {
        uint256 principal;
        uint256 ltv;
        uint256 fee;
        uint256 netAmount;
    }

    struct RepayView {
        uint256 collateralRatio;
        uint256 collateralReturned;
        uint256 principal;
    }

    /// @notice One legacy card, per design doc §10.
    struct LegacyPositionView {
        uint256 collateral;        // VY locked
        uint256 principal;         // asset owed
        uint256 accruedInterest;   // VY
        uint256 netCollateral;     // VY the borrower would actually free
        uint256 costToUnlockAsset; // principal, in asset units
        uint256 surchargeAsset;    // the +unlockBps premium, in asset units
        uint256 claimableVy;       // matured tranches, claimable now
        uint256 lockedVy;          // freed but still inside the lock
        uint64 nextUnlockAt;       // soonest maturity among locked tranches (0 if none)
    }

    constructor(address vloAddress, address daxAddress) {
        if (vloAddress == address(0) || daxAddress == address(0)) revert InvalidAddress();
        vlo = ILensVlo(vloAddress);
        dax = ILensDax(daxAddress);
    }

    // ═══════════════════════════ ASSET-LOAN LANE ═════════════════════════════

    /// @notice GROSS quote: what `collateral` VY is worth at the current LTV, with the
    ///         1% origination fee NOT deducted.
    /// @dev ⚠️ This is ~1% ABOVE what {ValinityLoanOfficer-openLoan} actually pays,
    ///      because the officer sizes the loan on `collateral − fee`. Kept at these
    ///      semantics because the pre-V13 officer's `getBorrowQuote` behaved
    ///      identically and off-chain consumers compensate for it. **For anything a
    ///      user sees, use {getNewLoanView}**, whose `principal` is what lands in the
    ///      wallet to the wei (fork-verified).
    function getBorrowQuote(address asset, uint256 collateral) public view returns (uint256) {
        return _toPrincipal(_decimals(asset), vlo.getLTV(asset), collateral);
    }

    function getAssetView(address asset) external view returns (AssetView memory) {
        return AssetView({
            ltv: vlo.getLTV(asset),
            reserveBalance: poolAssetOf(asset),
            totalLoaned: vlo.getTotalLoaned(asset)
        });
    }

    /// @notice Preview a new loan. The fee is 1% of the VY collateral; the borrower
    ///         receives the full principal.
    function getNewLoanView(
        address asset,
        uint256 collateral
    ) external view returns (NewLoanView memory) {
        uint256 fee = (collateral * vlo.processingFeePercentage()) / BPS;
        uint256 ltv = vlo.getLTV(asset);
        uint256 principal = _toPrincipal(_decimals(asset), ltv, collateral - fee);
        return NewLoanView({principal: principal, ltv: ltv, fee: fee, netAmount: principal});
    }

    /// @notice What actually bounds a new loan.
    /// @dev V10: the cap/floor limit is gone with the cap ledger. What remains is the
    ///      asset's DAX pool leg (the reserve a draw comes out of) and the per-
    ///      operation anti-whale cap in `loanCapBps`.
    function getLoanConstraints(
        address asset,
        uint256 collateralBalance
    ) external view returns (LoanConstraintsView memory) {
        uint8 dec = _decimals(asset);
        uint256 ltv = vlo.getLTV(asset);
        if (ltv == 0 || collateralBalance == 0) {
            return LoanConstraintsView({maxCollateral: 0, maxPrincipal: 0});
        }

        uint256 maxCollateral = collateralBalance;
        uint256 capLimit = (vlo.getTotalCirculatingVY() * vlo.loanCapBps()) / BPS;
        if (maxCollateral > capLimit) maxCollateral = capLimit;

        uint256 maxPrincipal = _toPrincipal(dec, ltv, maxCollateral);
        // Quote against what the draw can ACTUALLY take: the pool's asset leg LESS
        // the VY-loan collateral the officer's `_distributeLoan` refuses to touch.
        // Quoting the gross leg hands the UI a number that reverts
        // ReserveFloorBreached on execution — fork-measured at exactly
        // vyLoanCollateralPerAsset once the pool (not the per-call cap) binds.
        uint256 reserve = poolAssetOf(asset);
        uint256 owed = vlo.vyLoanCollateralPerAsset(asset);
        reserve = reserve > owed ? reserve - owed : 0;
        if (maxPrincipal > reserve) {
            maxPrincipal = reserve;
            // Clamp DOWN only — mirrors the officer; see its note on the inverse-
            // rounding gap that can otherwise push maxCollateral above the balance.
            uint256 need = _toCollateral(dec, ltv, maxPrincipal);
            if (need < maxCollateral) maxCollateral = need;
        }
        return LoanConstraintsView({maxCollateral: maxCollateral, maxPrincipal: maxPrincipal});
    }

    /// @notice The borrower's NORMAL-book position — the one {repayLoan} settles.
    /// @dev Legacy positions have their own card, {getLegacyPositionView}.
    function getLoanView(address borrower, address asset) external view returns (LoanView memory) {
        (Loan memory n, uint256 accrued) = _normalBook(borrower, asset);
        return _view(n, accrued, asset, true);
    }

    /// @notice Preview {repayLoan}. Quotes the NORMAL book only, which is the only
    ///         book that function touches.
    function getRepayView(
        address borrower,
        address asset,
        uint256 payment
    ) external view returns (RepayView memory) {
        (Loan memory l, uint256 accrued) = _normalBook(borrower, asset);
        if (l.openedAt == 0) return RepayView(0, 0, 0);
        if (payment > l.principal) revert PaymentTooHigh();

        uint256 net = l.collateral - accrued;
        // Underwater: any payment auto-closes and the borrower gets zero VY back.
        if (net == 0) return RepayView({collateralRatio: 0, collateralReturned: 0, principal: 0});

        uint256 returned = (net * payment) / l.principal;
        return RepayView({
            collateralRatio: (returned * WAD) / net,
            collateralReturned: returned,
            principal: l.principal - payment
        });
    }

    /**
     * @notice The NORMAL-book slot alone, with its interest accrued correctly.
     *
     * @dev WHY THIS EXISTS. {ILensVlo-getLoan} returns the normal and legacy books
     *      SUMMED, carrying the EARLIER of the two clocks — the officer does that
     *      deliberately so VBSO's coverage test keeps working. Accruing on that
     *      merged struct then charges the WHOLE merged balance from the older slot's
     *      timestamp, and caps one combined total instead of capping each slot at its
     *      own collateral. The officer states the rule in {getAccruedInterest}:
     *      accrue per slot and sum, never on a field-wise merge.
     *
     *      Measured on a mainnet fork before this fix: a legacy borrower who opened a
     *      normal loan showed 67.14 VY of accrued interest against a true 17.16 VY —
     *      a **291% overstatement**, which understates the collateral they get back
     *      and can paint a healthy position as underwater. 378 legacy borrowers are
     *      one `openLoan` away from that state.
     *
     *      The reconstruction is exact: the money fields subtract cleanly, and the
     *      accrual comes from the officer's own correct total minus the legacy slice
     *      (computed against the legacy slot's OWN clock, which
     *      {getLegacyPosition} exposes).
     *
     *      LIMITATION — timestamps. When a legacy slot is present, `agg` carries the
     *      earlier clock and the normal slot's own `openedAt` / `interestAppliedAt`
     *      are not recoverable from the officer's public surface. They are returned
     *      as-is and are COSMETIC ONLY; every money field is exact.
     */
    function _normalBook(
        address borrower,
        address asset
    ) internal view returns (Loan memory n, uint256 accrued) {
        // `isActive` is the officer's un-aggregated existence flag for this slot.
        if (!vlo.isActive(borrower, asset)) return (n, 0);

        Loan memory agg = vlo.getLoan(borrower, asset);
        (Loan memory g, ) = vlo.getLegacyPosition(borrower, asset);

        n.collateral = agg.collateral - g.collateral;
        n.principal = agg.principal - g.principal;
        n.interestCarry = agg.interestCarry - g.interestCarry;
        n.openedAt = agg.openedAt; // cosmetic — see the note above
        n.interestAppliedAt = agg.interestAppliedAt;

        accrued = vlo.getAccruedInterest(borrower, asset) - _accrued(g);
        if (accrued > n.collateral) accrued = n.collateral;
    }

    // ═══════════════════════════ VY-LOAN LANE ════════════════════════════════

    /// @notice VY principal borrowable against `assetCollateral`, over-collateralized
    ///         per `marketLtvBps`.
    /// @dev V14: calls {VLOLegacyLib-vyQuoteOf} — the EXACT function
    ///      {ValinityLoanOfficer-_quoteVyPrincipal} mints against — rather than
    ///      reimplementing it, so the screen figure and the minted amount cannot drift.
    ///      This matters now that the officer takes min(oracle, pool spot): the previous
    ///      oracle-only copy here would OVER-quote whenever the pool term binds, which
    ///      it does on the VY lane today.
    ///
    ///      Note the failure mode changed with it: a dead oracle leg now REVERTS
    ///      `NoPrice` exactly as the officer does, instead of silently returning 0.
    function getVyBorrowQuote(
        address asset,
        uint256 assetCollateral
    ) external view returns (uint256) {
        (address oracle, address assetTwap) = vlo.priceSources();
        return VLOLegacyLib.vyQuoteOf(
            oracle, assetTwap, address(dax), asset,
            assetCollateral, vlo.marketLtvBps(), _decimals(asset)
        );
    }

    function getVyLoanView(address borrower, address asset) external view returns (LoanView memory) {
        // The VY book is never aggregated with anything — one slot, one clock.
        Loan memory l = vlo.getVyLoan(borrower, asset);
        return _view(l, _accrued(l), asset, false);
    }

    /// @notice Largest VY payment {repayVyLoan} accepts right now.
    /// @dev V14: the anti-whale term is GONE — repayments are uncapped, because a
    ///      repayment shrinks protocol exposure and rationing it can strand a close.
    ///      The asset's DAX pool leg is the only bound left, and it is the same one the
    ///      on-chain gate checks, so this is exact rather than optimistic.
    function getMaxVyRepayable(address borrower, address asset) external view returns (uint256) {
        Loan memory l = vlo.getVyLoan(borrower, asset);
        if (l.openedAt == 0) return 0;
        uint256 net = l.collateral - _accrued(l);
        if (net == 0) return l.principal; // underwater: whole payment is interest

        uint256 maxPay = (poolAssetOf(asset) * l.principal) / net;
        return maxPay < l.principal ? maxPay : l.principal;
    }

    // ═════════════════════════════ LEGACY LANE ═══════════════════════════════

    /// @notice The legacy card of design doc §10 — everything needed to render
    ///         "cost to unlock = X asset + $Y premium", plus the lock state.
    function getLegacyPositionView(
        address borrower,
        address asset
    ) external view returns (LegacyPositionView memory v) {
        (Loan memory l, LegacyUnlock[] memory q) = vlo.getLegacyPosition(borrower, asset);

        if (l.openedAt != 0) {
            v.collateral = l.collateral;
            v.principal = l.principal;
            v.accruedInterest = _accrued(l);
            v.netCollateral = l.collateral - v.accruedInterest;
            v.costToUnlockAsset = l.principal;
            // Priced on the VY the borrower would actually free — the interest slice
            // goes to VBBO and never reaches them, so it is never surcharged.
            v.surchargeAsset = quoteLegacySurcharge(asset, v.netCollateral);
        }

        uint64 soonest = type(uint64).max;
        for (uint256 i = 0; i < q.length; ) {
            if (q[i].unlockAt <= block.timestamp) {
                v.claimableVy += q[i].vy;
            } else {
                v.lockedVy += q[i].vy;
                if (q[i].unlockAt < soonest) soonest = q[i].unlockAt;
            }
            unchecked { ++i; }
        }
        if (soonest != type(uint64).max) v.nextUnlockAt = soonest;
    }

    /// @notice Live surcharge for freeing `vyFreed` of legacy collateral, in asset units.
    /// @dev Calls the SAME library function the repay path charges with, so the
    ///      screen figure and the charged figure cannot diverge. Returns 0 when the
    ///      surcharge is disabled (`unlockBps == 0`).
    function quoteLegacySurcharge(address asset, uint256 vyFreed) public view returns (uint256) {
        (address oracle, address assetTwap) = vlo.priceSources();
        (uint16 bps, , uint128 minVy, , , ) = vlo.legacyConfig();
        return VLOLegacyLib.surchargeOf(
            oracle, assetTwap, asset, vyFreed, bps, minVy, _decimals(asset)
        );
    }

    /// @notice Total cost to fully unlock a legacy position, both legs.
    function quoteLegacyUnlock(
        address borrower,
        address asset
    ) external view returns (uint256 repayAsset, uint256 surchargeAsset, uint256 vyFreed) {
        (Loan memory l, ) = vlo.getLegacyPosition(borrower, asset);
        if (l.openedAt == 0) return (0, 0, 0);
        vyFreed = l.collateral - _accrued(l);
        repayAsset = l.principal;
        surchargeAsset = quoteLegacySurcharge(asset, vyFreed);
    }

    // ═════════════════════════════ INTERNALS ═════════════════════════════════

    /// @notice The asset leg of `asset`'s DAX pool — V10's reserve balance.
    function poolAssetOf(address asset) public view returns (uint256) {
        if (!dax.hasPool(asset)) return 0;
        (, , uint256 reserveAsset) = dax.getPoolReserves(dax.assetToPoolId(asset));
        return reserveAsset;
    }

    /// @dev Mirrors the officer's `_accrued`: carry plus fresh accrual, capped at
    ///      the collateral. At the cap the position is underwater / rent-to-own complete.
    function _accrued(Loan memory l) internal view returns (uint256) {
        if (l.openedAt == 0) return 0;
        uint256 total = l.interestCarry +
            (l.collateral * vlo.interestRatePerSecond() * (block.timestamp - l.interestAppliedAt)) / WAD;
        return total > l.collateral ? l.collateral : total;
    }

    /// @param accrued Interest for THIS slot, passed in rather than recomputed: the
    ///        asset lane's figure has to be reconstructed in {_normalBook} and must
    ///        not be re-derived from a merged struct here.
    /// @param assetIsPrincipal true for the asset lane (principal is the asset,
    ///        collateral is VY); false for the VY lane, where they swap.
    function _view(
        Loan memory l,
        uint256 accrued,
        address asset,
        bool assetIsPrincipal
    ) internal view returns (LoanView memory) {
        if (l.openedAt == 0) return LoanView(0, 0, 0, 0, 0, 0, 0, 0);
        uint256 net = l.collateral - accrued;
        uint256 ltv;
        if (net > 0) {
            if (assetIsPrincipal) {
                ltv = (_scale(l.principal, _decimals(asset), DEFAULT_DECIMALS) * WAD) / net;
            } else {
                uint256 netNorm = _scale(net, _decimals(asset), DEFAULT_DECIMALS);
                if (netNorm > 0) ltv = (l.principal * WAD) / netNorm;
            }
        }
        return LoanView({
            collateral: l.collateral,
            principal: l.principal,
            openedAt: l.openedAt,
            interestAppliedAt: l.interestAppliedAt,
            ltv: ltv,
            accruedInterest: accrued,
            netCollateral: net,
            interestCarry: l.interestCarry
        });
    }

    function _toPrincipal(uint8 dec, uint256 ltv, uint256 collateral) internal pure returns (uint256) {
        return _scale((collateral * ltv) / WAD, DEFAULT_DECIMALS, dec);
    }

    function _toCollateral(uint8 dec, uint256 ltv, uint256 principal) internal pure returns (uint256) {
        if (ltv == 0) return 0;
        return (_scale(principal, dec, DEFAULT_DECIMALS) * WAD) / ltv;
    }

    function _scale(uint256 amount, uint8 from, uint8 to) internal pure returns (uint256) {
        unchecked {
            if (from > to) return amount / 10 ** (from - to);
            if (from < to) return amount * 10 ** (to - from);
            return amount;
        }
    }

    function _decimals(address asset) internal view returns (uint8) {
        try IERC20Metadata(asset).decimals() returns (uint8 d) {
            return d;
        } catch {
            return DEFAULT_DECIMALS;
        }
    }
}

@openzeppelin/contracts/token/ERC20/IERC20.sol

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

pragma solidity >=0.4.16;

/**
 * @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);
}

@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol

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

pragma solidity >=0.6.2;

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);
}

contracts/officer/VLOLegacyLib.sol

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

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

// ─────────────────────────────────────────────────────────────────────────────
// FILE-LEVEL TYPES. Declared here rather than inside the library so BOTH the
// officer and the library name them unqualified — the officer's existing
// `Loan storage loan = ...` bodies are untouched, and storage layout and ABI
// encoding are byte-identical to the pre-library declarations.
// ─────────────────────────────────────────────────────────────────────────────

struct Loan {
    uint256 collateral; // VY locked in the VCT for this loan (gross, before carry)
    uint256 principal; // Asset loaned to borrower
    uint64 openedAt; // Timestamp when loan was opened
    uint64 interestAppliedAt; // Last time interest was crystallized into carry
    uint256 interestCarry; // Accrued interest owed, not yet settled.
                           //   Effective user claim = collateral - interestCarry.
}

/// @notice One freed-but-locked legacy tranche. Packs into a single slot
///         (16 + 8 bytes). `vy` fits uint128 with ~13 orders to spare — the
///         entire legacy book is 1.008e25 against a 3.4e38 ceiling.
struct LegacyUnlock {
    uint128 vy; // VY freed by one repayment, held in the VCT
    uint64 unlockAt; // when this tranche becomes claimable
}

interface ILibVct {
    function applyInterest(address asset, uint256 vyAmount, address recipient) external;
}

interface ILibDax {
    function reserveInjectAsset(uint256 poolId, uint256 assetAmount) external;
}

interface ILibVmmo {
    /// @notice Equity donation door. PULLS via transferFrom and credits
    ///         `books[asset].held`, which is the only ledger VMMO's coverage,
    ///         deploy and payout paths read.
    function donateAsset(address asset, uint256 amount) external;
}

interface ILibDaxDraw {
    function reserveExtractAsset(uint256 poolId, uint256 assetAmount, address recipient)
        external returns (uint256);
    function getPoolReserves(uint256 poolId)
        external view returns (address asset, uint256 reserveVY, uint256 reserveAsset);
    function hasPool(address asset) external view returns (bool);
    function assetToPoolId(address asset) external view returns (uint256);
}

interface ILibWeth {
    function deposit() external payable;
}

/// @dev Everything the shared repay core needs that is not a storage pointer.
///      Packed into one memory struct because the function would otherwise blow the
///      stack even under viaIR.
struct RepayCtx {
    address vct;
    address dax;
    address weth;
    address vmmo;
    address vyToken;
    address vyOracle;
    address assetOracle;
    address interestRecipient;
    address underwaterRecipient;
    address borrower;
    address asset;
    uint256 poolId;
    uint256 payment;
    uint256 maxSurcharge;
    uint256 rate;
    uint256 msgValue;
    uint16 unlockBps;
    uint32 lockPeriod;
    uint128 minVyUsd;
    uint8 assetDecimals;
    uint8 maxOpenUnlocks;
    bool legacy;
    bool nativeEth;
}

interface ILibVyOracle {
    function vyPerUsdcX112() external view returns (uint224);
    /// @notice Median EXCLUDING the direct UniV2 leg.
    function vyPerUsdcExDirectX112() external view returns (uint224);
}

interface ILibAssetOracle {
    function getAssetTwapPrice(address asset) external view returns (uint256);
}

/**
 * @title VLOLegacyLib
 * @notice The bytecode-heavy half of the legacy unlock surcharge, split out of
 *         {ValinityLoanOfficer} for EIP-170 room.
 *
 * @dev DELEGATECALL library (precedent: VMMOCoverageLib, VSRZapLib). Every
 *      function takes the officer's own storage pointers, so `address(this)` is
 *      the officer and all state written here is the officer's.
 *
 *      WHY THIS EXISTS: V11 pushed VLO to 27,848 bytes against the 24,576 ceiling.
 *      `runs: 1` + `viaIR` were ALREADY applied to VLO before this work (see
 *      hardhat.config.ts), so the optimizer had nothing left to give — the split
 *      was the only remaining lever.
 */
library VLOLegacyLib {
    uint256 internal constant WAD = 1e18;
    uint16 internal constant BPS = 10_000;

    error SeedMismatch();
    error NoPrice();
    error VyPriceTooLow();
    error InvalidRow();
    error ReserveFloorBreached();
    error AlreadyMigrated();

    event LegacyLoanMigrated(
        address indexed borrower,
        address indexed asset,
        uint256 collateral,
        uint256 principal
    );
    event LegacyMigrationFinalized(uint256 rowCount);

    // ═════════════════════════════ MIGRATION ═════════════════════════════════

    /**
     * @notice Move migrated positions out of `loans` into `legacyLoans`.
     * @dev No tokens move — collateral stays in the VCT throughout.
     *
     *      ⚠️ `openedAt` and `interestAppliedAt` MUST carry over untouched.
     *      Resetting them restarts the 11.99%/yr clock and hands back interest
     *      already accrued (376,266.69 VY cohort-wide, and real money on the top
     *      borrower alone).
     *
     *      ⚠️ `wipeNormal` must `delete` the whole slot, not zero its fields.
     *      `isActive` is `openedAt > 0`, so a slot left with a live timestamp and
     *      zero balances permanently bricks `openLoan` (ActiveLoanExists) and
     *      `repayLoan` (PaymentTooHigh) for that address — the exact failure the
     *      1,106 delete rows exist to avoid.
     */
    function migrateBatch(
        mapping(address => mapping(address => Loan)) storage legacyLoans,
        mapping(address => mapping(address => Loan)) storage loans,
        mapping(address => uint256) storage legacyCollateralPerAsset,
        mapping(address => uint256) storage legacyPrincipalPerAsset,
        mapping(address => uint256) storage legacyCarryPerAsset,
        address[] calldata borrowers,
        address[] calldata assets,
        Loan[] calldata rows,
        bool[] calldata wipeNormal,
        Loan[] calldata normalRows
    ) external returns (uint256 written) {
        uint256 len = borrowers.length;
        if (
            assets.length != len || rows.length != len ||
            wipeNormal.length != len || normalRows.length != len
        ) {
            revert InvalidRow();
        }
        for (uint256 i = 0; i < len; ) {
            address b = borrowers[i];
            address a = assets[i];
            Loan calldata r = rows[i];
            // A 1,112-row admin batch with a bad row is permanently confiscatory:
            // a zero `openedAt` orphans the position, a future timestamp underflows
            // the accrual, and carry above collateral makes it instantly underwater.
            if (
                r.openedAt == 0 || r.interestAppliedAt == 0 ||
                r.openedAt > block.timestamp || r.interestAppliedAt > block.timestamp ||
                r.collateral == 0 || r.principal == 0 ||
                r.interestCarry > r.collateral
            ) revert InvalidRow();

            // Idempotency: a resent batch would otherwise double-count every
            // accumulator, permanently defeating finalize while the protocol stays
            // frozen behind `_migrationInProgress`. Revert loudly instead.
            if (legacyLoans[b][a].openedAt != 0) revert AlreadyMigrated();

            legacyLoans[b][a] = r;
            legacyCollateralPerAsset[a] += r.collateral;
            legacyPrincipalPerAsset[a] += r.principal;
            legacyCarryPerAsset[a] += r.interestCarry;
            // Two cases, and only these two. 1,106 of the 1,112 rows are wholly
            // legacy → delete the slot outright. The other 6 are genuinely blended →
            // overwrite with the normal remainder. Folded in here rather than a
            // second admin call so a row can never be half-migrated between txs.
            if (wipeNormal[i]) {
                delete loans[b][a];
            } else {
                // A blended slot's remainder gets the same validation: a zero
                // `openedAt` here both bricks the normal loan (isActive is
                // `openedAt > 0`) and lets the borrower's next openLoan write a
                // fresh slot over live collateral.
                Loan calldata n = normalRows[i];
                // Same balance check the legacy row gets. A blended remainder is by
                // definition non-empty; an empty one should have been wipeNormal=true.
                // Writing a zero-balance slot with a live `openedAt` bricks openLoan
                // (ActiveLoanExists) and repayLoan (PaymentTooHigh) for that borrower
                // forever — the exact failure the delete rows exist to avoid.
                if (
                    n.openedAt == 0 || n.interestAppliedAt == 0 ||
                    n.openedAt > block.timestamp || n.interestAppliedAt > block.timestamp ||
                    n.collateral == 0 || n.principal == 0 ||
                    n.interestCarry > n.collateral
                ) revert InvalidRow();
                loans[b][a] = n;
            }

            emit LegacyLoanMigrated(b, a, r.collateral, r.principal);
            unchecked { ++i; }
        }
        written = len;
    }

    /**
     * @notice Verify the migration against the off-chain dataset.
     * @dev Rejects the whole thing on any mismatch rather than leaving it
     *      half-applied. The reference figures are independently recomputable
     *      on-chain from the 1,373 `LoanEvent` logs, so anyone can check them.
     */
    function finalize(
        mapping(address => uint256) storage legacyCollateralPerAsset,
        mapping(address => uint256) storage legacyPrincipalPerAsset,
        mapping(address => uint256) storage legacyCarryPerAsset,
        uint256 actualRowCount,
        address[] calldata assets,
        uint256[][3] calldata totals,
        uint256 expectedRowCount
    ) external {
        // Collateral ALONE is not enough. A wrong principal split still reconciles on
        // collateral but underflows `_totalLoanedPerAsset` on the first repay, which
        // bricks the position permanently. The design doc's finalize() assertions
        // name all three; check all three.
        if (
            assets.length != totals[0].length ||
            assets.length != totals[1].length ||
            assets.length != totals[2].length
        ) revert InvalidRow();
        if (actualRowCount != expectedRowCount) revert SeedMismatch();
        for (uint256 i = 0; i < assets.length; ) {
            address a = assets[i];
            if (
                legacyCollateralPerAsset[a] != totals[0][i] ||
                legacyPrincipalPerAsset[a] != totals[1][i] ||
                legacyCarryPerAsset[a] != totals[2][i]
            ) revert SeedMismatch();
            unchecked { ++i; }
        }
        emit LegacyMigrationFinalized(expectedRowCount);
    }

    // ══════════════════════════════ REPAY ════════════════════════════════════

    error PaymentTooLow();
    error PaymentTooHigh();
    error MismatchedETHValue();
    error ETHNotAccepted();
    error SurchargeExceedsMax(uint256 required);
    error TooManyUnlocks();
    error InvalidAddress();
    error ETHTransferFailed();

    /// @dev Enum encodes as uint8 in the canonical signature, so this declaration
    ///      produces the SAME topic0 as the officer's `LoanEvent`. Emitted under the
    ///      officer's address because this library runs by DELEGATECALL.
    event LoanEvent(
        uint8 indexed eventType, address indexed borrower, address indexed asset,
        int256 deltaCollateral, int256 deltaPrincipal, uint256 processingFeeAmount,
        uint256 interestFeeAmount, uint256 totalCollateral, uint256 totalPrincipal
    );
    event InterestAccruedToVRO(address indexed borrower, uint256 amount, uint256 total);
    event LegacyUnlockPurchased(
        address indexed borrower, address indexed asset,
        uint256 vyFreed, uint256 surcharge, uint64 unlockAt
    );
    /// @notice The VMMO route refused a repayment and it went to the pool instead.
    ///         Not an error — the designed fallback — but worth alerting on: a
    ///         steady stream means VMMO is unlisted, paused or misconfigured.
    event RepayRouteFallback(address indexed asset, uint256 amount);

    uint8 internal constant EV_REPAID = 2;
    uint8 internal constant EV_LIQUIDATED = 4;

    /// @dev Intermediates held in MEMORY, not on the stack. Nine live locals plus
    ///      six storage pointers overflowed the 16-slot EVM stack even under viaIR;
    ///      one memory pointer costs one slot.
    struct RepayVars {
        uint256 collateral;
        uint256 principal;
        uint256 totalInterest;
        uint256 netCollateral;
        uint256 collateralReturned;
        uint256 interestCharged;
        uint256 surcharge;
        uint256 totalVyRelease;
        uint256 refund;
        uint256 carrySub;
    }

    /**
     * @notice The single repay core, shared by the normal and legacy lanes.
     * @dev `c.legacy` selects two behaviours and nothing else: the unlock surcharge,
     *      and whether the freed VY goes to the borrower or into a locked tranche.
     *      The interest accrual, the pro-rata split, the pool re-injection and the
     *      VBBO interest routing are identical — which is the point of sharing this.
     *
     *      Lives in the library purely for EIP-170 room; it is the largest function
     *      in the officer and well above the ~200-byte delegatecall break-even.
     * @return refund Native ETH owed back to the borrower (ETH lane over-payment).
     */
    function repayCore(
        Loan storage loan,
        LegacyUnlock[] storage q,
        mapping(address => uint256) storage totalLoanedPerAsset,
        mapping(address => uint256) storage carryAgg,
        mapping(address => uint256) storage legacyCollateralPerAsset,
        mapping(address => uint256) storage cumulativeInterest,
        RepayCtx memory c
    ) external returns (uint256 refund, uint256 lockedAdded) {
        RepayVars memory v;
        v.collateral = loan.collateral;
        v.principal = loan.principal;
        v.carrySub = loan.interestCarry;

        // REPAY-ALL. A loan closes only on an EXACT principal match, and principal
        // is an 18-dp integer — a caller that sends a displayed or rounded figure
        // is short by a few wei and the slot stays open, still holding collateral
        // and still blocking `openLoan` (isActive is `openedAt > 0`). 116 live
        // positions across 51 addresses are stuck exactly that way. `max` lets the
        // caller say "everything" without naming a number it can get wrong.
        // Resolved BEFORE the bounds checks, so the value they guard is the real one.
        if (c.payment == type(uint256).max) c.payment = v.principal;
        if (c.payment == 0) revert PaymentTooLow();
        if (c.payment > v.principal) revert PaymentTooHigh();

        v.totalInterest = v.carrySub +
            (v.collateral * c.rate * (block.timestamp - loan.interestAppliedAt)) / WAD;
        if (v.totalInterest > v.collateral) v.totalInterest = v.collateral;
        v.netCollateral = v.collateral - v.totalInterest;

        if (v.netCollateral != 0) {
            v.collateralReturned = (v.netCollateral * c.payment) / v.principal;
            v.interestCharged = (v.totalInterest * c.payment) / v.principal;
        }

        // Surcharge on the VY the borrower actually frees. The interest slice goes to
        // VBBO and never reaches them, so it is never surcharged.
        if (c.legacy && v.collateralReturned > 0) {
            v.surcharge = surchargeOf(
                c.vyOracle, c.assetOracle, c.asset, v.collateralReturned,
                c.unlockBps, c.minVyUsd, c.assetDecimals
            );
            if (v.surcharge > c.maxSurcharge) revert SurchargeExceedsMax(v.surcharge);
        }

        {
            uint256 due = c.payment + v.surcharge;
            if (c.nativeEth) {
                // `>=` not `==`. The surcharge moves every second (interest accrual
                // plus two TWAPs), so a borrower cannot pre-compute the exact wei —
                // equality made the ETH lane revert on essentially every attempt and
                // rendered `maxSurcharge` dead. Over-payment is refunded.
                if (c.msgValue < due) revert MismatchedETHValue();
                unchecked { v.refund = c.msgValue - due; }
                ILibWeth(c.weth).deposit{value: due}();
            } else {
                if (c.msgValue > 0) revert ETHNotAccepted();
                _pull(c.asset, c.borrower, due);
            }
        }

        if (v.surcharge > 0) {
            if (c.vmmo == address(0)) revert InvalidAddress();
            // MUST go through {donateAsset}, never a bare transfer. VMMO accounts by
            // its internal `books[asset].held`, not by balance: the only writers are
            // deposit / levy / renew-recall, `heldOf` reads that mapping, objective 1
            // deploys from it and `_pay` is clamped by it — and VMMO has no rescue
            // function. A plain transfer in is invisible to coverage, undeployable,
            // unpayable and unrecoverable by anyone including admin. `donateAsset`
            // PULLS, so approve first. It also requires the asset to be listed on
            // VMMO — a wiring precondition, not something this call can fix.
            _approve(c.asset, c.vmmo, v.surcharge);
            ILibVmmo(c.vmmo).donateAsset(c.asset, v.surcharge);
        }

        // ── Where the repayment goes ────────────────────────────────────────
        // Preferred: VMMO. It does not merely park the asset — `_deployOne` runs
        // it through `swapExactIn` on the DAX, so the asset lands in the SAME
        // pool's asset leg AND buys VY out of it, delivered to VBBO. Same
        // destination as a bare inject, plus a real bid, paced and band-gated.
        //
        // SOFT-FAILS TO THE POOL, and that is the whole design of this block. A
        // repayment must never be blockable by a third contract's state: if VMMO
        // is unset, not yet deployed, has the asset unlisted, is paused, or
        // reverts for any reason, the asset goes straight back to the pool it came
        // from — the pre-V13 behaviour, unchanged. Without this fallback, listing
        // an asset on VMMO becomes a precondition for ANY borrower to repay ANY
        // loan, and a VMMO outage would trap the entire book.
        bool routed;
        if (c.vmmo != address(0)) {
            _approve(c.asset, c.vmmo, c.payment);
            try ILibVmmo(c.vmmo).donateAsset(c.asset, c.payment) {
                routed = true;
            } catch {
                emit RepayRouteFallback(c.asset, c.payment);
            }
        }
        if (!routed) {
            _approve(c.asset, c.dax, c.payment);
            ILibDax(c.dax).reserveInjectAsset(c.poolId, c.payment);
        }

        // ---- Underwater: interest consumed the claim. Borrower gets zero, so there
        //      was nothing to surcharge either.
        if (v.netCollateral == 0) {
            ILibVct(c.vct).applyInterest(c.asset, v.collateral, c.underwaterRecipient);
            totalLoanedPerAsset[c.asset] -= v.principal;
            _subAgg(carryAgg, c.asset, v.carrySub);
            if (c.legacy) legacyCollateralPerAsset[c.asset] -= v.collateral;
            _wipe(loan);
            emit LoanEvent(
                EV_REPAID, c.borrower, c.asset, -int256(v.collateral),
                -int256(v.principal), 0, v.collateral, 0, 0
            );
            return (v.refund, 0);
        }

        v.totalVyRelease = v.collateralReturned + v.interestCharged;

        // A legacy repay releases only the interest slice; the borrower's slice stays
        // in the VCT under lock, which keeps it out of circulating supply.
        {
            uint256 toBorrower = c.legacy ? 0 : v.collateralReturned;
            uint256 vyOut = v.interestCharged + toBorrower;
            // Guarded: `applyInterest` reverts ZeroAmount, and a legacy repay whose
            // interest slice floors to zero would otherwise brick where normal cannot.
            if (vyOut != 0) ILibVct(c.vct).applyInterest(c.asset, vyOut, address(this));
            if (v.interestCharged > 0) {
                _send(c.vyToken, c.interestRecipient, v.interestCharged);
                uint256 nt = cumulativeInterest[c.borrower] + v.interestCharged;
                cumulativeInterest[c.borrower] = nt;
                emit InterestAccruedToVRO(c.borrower, v.interestCharged, nt);
            }
            if (toBorrower > 0) _send(c.vyToken, c.borrower, toBorrower);
        }

        if (c.legacy) {
            if (v.collateralReturned > 0) {
                if (q.length >= c.maxOpenUnlocks) revert TooManyUnlocks();
                uint64 unlockAt = uint64(block.timestamp + c.lockPeriod);
                q.push(LegacyUnlock({vy: uint128(v.collateralReturned), unlockAt: unlockAt}));
                lockedAdded = v.collateralReturned;
                emit LegacyUnlockPurchased(
                    c.borrower, c.asset, v.collateralReturned, v.surcharge, unlockAt
                );
            }
            // OUTSIDE the tranche guard: `collateralReturned` floors to zero on a
            // small payment against a position whose interest has eaten most of the
            // claim, but `totalVyRelease` is still > 0 and the collateral still
            // shrinks below. Inside the guard the running total drifted permanently.
            legacyCollateralPerAsset[c.asset] -= v.totalVyRelease;
        }

        {
            uint256 aggC = carryAgg[c.asset];
            carryAgg[c.asset] = (aggC > v.carrySub ? aggC - v.carrySub : 0) +
                (v.totalInterest - v.interestCharged);
        }
        totalLoanedPerAsset[c.asset] -= c.payment;

        uint256 remaining = v.principal - c.payment;
        if (remaining == 0) {
            _wipe(loan);
        } else {
            loan.collateral = v.collateral - v.totalVyRelease;
            loan.interestCarry = v.totalInterest - v.interestCharged;
            loan.interestAppliedAt = uint64(block.timestamp);
            loan.principal = remaining;
        }

        // Report the position's ACTUAL post-repay totals. Emitting zeros here made
        // every partial repay look closed to indexers.
        emit LoanEvent(
            EV_REPAID, c.borrower, c.asset, -int256(v.totalVyRelease),
            -int256(c.payment), 0, v.interestCharged,
            remaining == 0 ? 0 : v.collateral - v.totalVyRelease, remaining
        );
        return (v.refund, lockedAdded);
    }

    function _wipe(Loan storage l) private {
        delete l.collateral;
        delete l.principal;
        delete l.openedAt;
        delete l.interestAppliedAt;
        delete l.interestCarry;
    }

    function _subAgg(mapping(address => uint256) storage m, address k, uint256 v) private {
        uint256 x = m[k];
        m[k] = x > v ? x - v : 0;
    }

    function _pull(address token, address from, uint256 amt) private {
        if (amt == 0) return;
        (bool ok, bytes memory d) = token.call(
            abi.encodeWithSelector(IERC20.transferFrom.selector, from, address(this), amt)
        );
        if (!ok || (d.length != 0 && !abi.decode(d, (bool)))) revert ETHTransferFailed();
    }

    function _send(address token, address to, uint256 amt) private {
        if (amt == 0) return;
        (bool ok, bytes memory d) = token.call(
            abi.encodeWithSelector(IERC20.transfer.selector, to, amt)
        );
        if (!ok || (d.length != 0 && !abi.decode(d, (bool)))) revert ETHTransferFailed();
    }

    function _approve(address token, address spender, uint256 amt) private {
        if (IERC20(token).allowance(address(this), spender) < amt) {
            (bool ok, ) = token.call(
                abi.encodeWithSelector(IERC20.approve.selector, spender, type(uint256).max)
            );
            if (!ok) revert ETHTransferFailed();
        }
    }

    // ═══════════════════════════ BUYBACK DRAW ════════════════════════════════

    event BuybackDraw(address indexed asset, uint256 vyRetired, uint256 assetOut);

    /**
     * @notice Retire VY into the VYT and draw the matching asset out of its DAX pool.
     * @dev NOT A LOAN — nothing recorded, no interest, never repaid. The VY does not
     *      come back: it lands in the VYT, which the circulating-supply formula
     *      excludes, so the supply reduction is immediate and permanent. The asset is
     *      the consideration, not a loan against the VY.
     *
     *      THE VY IS MEASURED, NOT ASSUMED. VY is fee-on-transfer for non-whitelisted
     *      parties, so the draw is sized on the balance delta the VYT actually
     *      observes — sizing on the requested amount would over-draw by the fee.
     *
     *      Delivered as ERC20 straight to `to`, deliberately NOT through the officer's
     *      `_extractAsset`, which unwraps WETH to native ETH for any address that is
     *      not a registered leverage clone. The buyback officer needs the ERC20 to
     *      route into USDC.
     */
    function buybackDraw(
        uint256 reserveFloor,
        address vyToken,
        address vyt,
        address dax,
        uint256 poolId,
        address asset,
        address to,
        uint256 vyAmount,
        uint256 ltv,
        uint8 assetDecimals
    ) external returns (uint256 assetOut) {
        uint256 pre = IERC20(vyToken).balanceOf(vyt);
        _pullTo(vyToken, to, vyt, vyAmount);
        uint256 retired = IERC20(vyToken).balanceOf(vyt) - pre;
        if (retired == 0) revert PaymentTooLow();

        uint256 raw = (retired * ltv) / WAD; // 18-dp asset
        assetOut = assetDecimals >= 18
            ? raw * (10 ** (assetDecimals - 18))
            : raw / (10 ** (18 - assetDecimals));
        if (assetOut == 0) revert PaymentTooLow();

        // VY-loan collateral lives in this pool and must stay extractable on repay.
        // A buyback draw is permanent and unrecorded, so without this floor it can
        // consume borrower property that the protocol still owes back.
        if (reserveFloor != 0) {
            (, , uint256 leg) = ILibDaxDraw(dax).getPoolReserves(poolId);
            if (leg < assetOut || leg - assetOut < reserveFloor) revert ReserveFloorBreached();
        }
        ILibDaxDraw(dax).reserveExtractAsset(poolId, assetOut, to);
        emit BuybackDraw(asset, retired, assetOut);
    }

    function _pullTo(address token, address from, address to, uint256 amt) private {
        (bool ok, bytes memory d) = token.call(
            abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, amt)
        );
        if (!ok || (d.length != 0 && !abi.decode(d, (bool)))) revert ETHTransferFailed();
    }

    // ═════════════════════════════ PRICING ═══════════════════════════════════

    /**
     * @notice Surcharge, in ASSET units, to free `vyFreed` of legacy collateral.
     * @dev    surchargeUsd   = vyFreed × vyUsd × unlockBps / 1e4
     *         surchargeAsset = ceil(surchargeUsd / assetUsd)
     *
     *      ⚠️ READS A DIFFERENT MARK FROM THE LOAN LANES, DELIBERATELY. Loans price
     *      off `vyPerUsdcX112` (the full median-of-four). This prices off
     *      `vyPerUsdcExDirectX112`, which drops the public UniV2 leg. The attack
     *      directions are opposite: a borrower wants the mark pushed UP to borrow
     *      more — expensive, and it moves real capital into the pools — but wants it
     *      pushed DOWN to buy a cheap unlock, and the thin Uni pair is the one venue
     *      an outsider can push cheaply. Do NOT "harmonise" these.
     *
     *      CEIL rounding is protocol-favoured and is what makes N small repays cost
     *      exactly what one large repay costs, so there is nothing to split around
     *      (the partial-repay bypass surface named in the design doc §4).
     *
     *      Both legs are TWAPs, so neither side is single-block manipulable. The
     *      `minVyUsd` floor stops a crashed or broken oracle pricing a cohort-wide
     *      fire sale.
     */
    // ═══════════════════════════ V14 — DUAL-SOURCE PRICING ═══════════════════
    // Both lanes price against TWO sources and hand out the LESSER of the two.
    //
    // WHY THE ORACLE ALONE IS NOT ENOUGH: it is a median of four, three legs of which
    // are TWAPs, so it reprices over hours. Fork-measured 2026-08-14: a drain took the
    // WETH pool's asset leg from 7.3718 to 1.6753 (−77%) while its VY leg never moved,
    // and the quoted LTV fell **0.26%**. The pool's own spot updates in the same
    // transaction the asset leaves; the oracle does not.
    //
    // WHY THE SPOT ALONE IS WORSE: the DAX is not sandwich-safe and its spot moves BOTH
    // ways, so quoting off it directly lets a borrower pump the pool and borrow against
    // the inflated rate — the exploit {reinitializeV9} closed (2026-08-05: the DAX
    // marked VY at ~$0.1826 against a ~$0.2903 market, 111% effective LTV).
    //
    // THE MINIMUM IS ONE-DIRECTIONAL AND THAT IS THE POINT: pushing the spot UP buys
    // nothing (the oracle caps it), while a real drain still collapses the pool term and
    // shuts the lane down. Measured in normal conditions the two sit on top of each
    // other (oracle 7.789e-5 vs pool 7.97e-5), so this is inert until it is needed.
    //
    // These live in the library, not the officer: adding them inline put VLO 133 bytes
    // OVER EIP-170.

    /// @dev Both legs of `asset`'s pool. (0,0) when the DAX or the pool is missing, so
    ///      callers fall back to the oracle term rather than reverting.
    function _legs(address dax, address asset)
        internal view returns (uint256 rVy, uint256 rAsset)
    {
        if (dax == address(0) || !ILibDaxDraw(dax).hasPool(asset)) return (0, 0);
        (, rVy, rAsset) = ILibDaxDraw(dax).getPoolReserves(ILibDaxDraw(dax).assetToPoolId(asset));
    }

    function _scaleDec(uint256 a, uint8 from, uint8 to) internal pure returns (uint256) {
        unchecked {
            if (from > to) return a / 10 ** (from - to);
            if (from < to) return a * 10 ** (to - from);
            return a;
        }
    }

    /// @notice ASSET LANE — 18-dp-normalized asset per VY, WAD-scaled, haircut to
    ///         `ltvBps`. The lesser of the oracle mark and the pool's live spot.
    function ltvOf(
        address vyOracle,
        address assetOracle,
        address dax,
        address asset,
        uint16 ltvBps,
        uint8 assetDecimals
    ) public view returns (uint256 ltv) {
        uint256 assetUsd = ILibAssetOracle(assetOracle).getAssetTwapPrice(asset);
        uint256 x = ILibVyOracle(vyOracle).vyPerUsdcX112();
        if (assetUsd == 0 || x == 0) revert NoPrice();
        uint256 usdPerVy = ((WAD * 1e12) << 112) / x; // 1e18 USD per whole VY
        ltv = (((usdPerVy * WAD) / assetUsd) * ltvBps) / BPS;

        (uint256 rVy, uint256 rAsset) = _legs(dax, asset);
        if (rVy != 0) {
            uint256 poolLtv =
                ((_scaleDec(rAsset, assetDecimals, 18) * WAD) / rVy) * ltvBps / BPS;
            if (poolLtv < ltv) ltv = poolLtv;
        }
    }

    /// @notice VY LANE — VY principal for `assetCollateral`, haircut to `ltvBps`.
    ///         Mirrored: this lane pays VY OUT, so safety is the LOWER VY amount.
    function vyQuoteOf(
        address vyOracle,
        address assetOracle,
        address dax,
        address asset,
        uint256 assetCollateral,
        uint16 ltvBps,
        uint8 assetDecimals
    ) public view returns (uint256 outVy) {
        uint256 assetUsd = ILibAssetOracle(assetOracle).getAssetTwapPrice(asset);
        uint256 x = ILibVyOracle(vyOracle).vyPerUsdcX112();
        if (assetUsd == 0 || x == 0) revert NoPrice();

        uint256 norm = _scaleDec(assetCollateral, assetDecimals, 18);
        uint256 collUsd = (norm * assetUsd) / WAD;
        outVy = ((((collUsd * x) / 1e12) >> 112) * ltvBps) / BPS;

        (uint256 rVy, uint256 rAsset) = _legs(dax, asset);
        uint256 rAssetNorm = _scaleDec(rAsset, assetDecimals, 18);
        if (rAssetNorm != 0) {
            uint256 poolVy = ((norm * rVy) / rAssetNorm) * ltvBps / BPS;
            if (poolVy < outVy) outVy = poolVy;
        }
    }

    function surchargeOf(
        address vyOracle,
        address assetOracle,
        address asset,
        uint256 vyFreed,
        uint16 unlockBps,
        uint128 minVyUsd,
        uint8 assetDecimals
    ) public view returns (uint256) {
        if (unlockBps == 0 || vyFreed == 0) return 0;

        // Take the HIGHER of the two marks — i.e. the worse one for whoever is
        // trying to manufacture a cheap unlock. The ex-direct median drops the thin
        // Uni pair (pushable down for a few thousand dollars), but its own three legs
        // ARE the DAX pools this contract drains, so a patient multi-block markdown
        // there buys a discount too. Requiring BOTH to fall means an attacker has to
        // hold down the DAX legs and the Uni pair simultaneously.
        uint256 xa = ILibVyOracle(vyOracle).vyPerUsdcExDirectX112();
        uint256 xb = ILibVyOracle(vyOracle).vyPerUsdcX112();
        if (xa == 0 || xb == 0) revert NoPrice();
        uint256 va = ((WAD * 1e12) << 112) / xa;
        uint256 vb = ((WAD * 1e12) << 112) / xb;
        uint256 vyUsd = va > vb ? va : vb; // 1e18 USD per whole VY
        if (vyUsd < minVyUsd) revert VyPriceTooLow();

        uint256 assetUsd = ILibAssetOracle(assetOracle).getAssetTwapPrice(asset);
        if (assetUsd == 0) revert NoPrice();

        uint256 surchargeUsd = (((vyFreed * vyUsd) / WAD) * unlockBps) / BPS;
        uint256 num = surchargeUsd * (10 ** assetDecimals);
        return (num + assetUsd - 1) / assetUsd; // ceil
    }

    // ══════════════════════════════ CLAIM ════════════════════════════════════

    /**
     * @notice Collect every matured tranche, up to `maxTranches` of them.
     * @dev Bounded by the caller so a long queue drains across several transactions
     *      rather than bricking on gas. Iterates BACKWARDS with swap-and-pop, which
     *      is what makes removal safe mid-loop: swapping the tail into `i` would
     *      skip an entry on a forward pass. Order is not preserved and does not
     *      matter — each tranche carries its own clock.
     */
    function claimUnlocks(
        LegacyUnlock[] storage q,
        address vct,
        address asset,
        address borrower,
        uint256 maxTranches
    ) external returns (uint256 claimed, uint256 processed) {
        for (uint256 i = q.length; i > 0 && processed < maxTranches; ) {
            unchecked { --i; }
            if (q[i].unlockAt > block.timestamp) continue;
            claimed += q[i].vy;
            unchecked { ++processed; }
            q[i] = q[q.length - 1];
            q.pop();
        }
        if (claimed != 0) {
            // Release from the VCT's collateral ledger straight to the borrower.
            ILibVct(vct).applyInterest(asset, claimed, borrower);
        }
    }

    // ════════════════════════════ LIQUIDATION ════════════════════════════════

    /**
     * @notice Permissionless batch liquidation of underwater LEGACY loans.
     * @dev Same semantics as the normal lane: the borrower receives zero and the
     *      whole collateral is routed to the VYT. No surcharge — nothing is freed
     *      to surcharge. Underwater means accrued interest has reached 100% of the
     *      collateral, which at 11.99%/yr is ~8.3 years out; verified 2026-08-08
     *      that 0 of the 1,112 legacy positions satisfy it today.
     */
    ///      Serves BOTH lanes: pass `loans` for the normal book or `legacyLoans` for
    ///      the legacy one. `trackLegacyTotal` is the only difference — the legacy
    ///      book maintains a per-asset running total that the normal book does not,
    ///      and decrementing it for a normal loan would underflow.
    function liquidateBook(
        mapping(address => mapping(address => Loan)) storage book,
        mapping(address => uint256) storage legacyCollateralPerAsset,
        mapping(address => uint256) storage totalLoanedPerAsset,
        address vct,
        address asset,
        address recipient,
        uint256 rate,
        bool trackLegacyTotal,
        address[] calldata borrowers
    ) external returns (uint256 liquidated, uint256 carryFreed, uint256 vyRouted) {
        uint256 len = borrowers.length;
        for (uint256 i = 0; i < len; ) {
            address borrower = borrowers[i];
            unchecked { ++i; }
            Loan storage loan = book[borrower][asset];
            if (loan.openedAt == 0) continue;

            uint256 collateral = loan.collateral;
            // A zero-collateral row trivially satisfies `interest >= collateral` and
            // would then revert `applyInterest` (ZeroAmount), taking the whole
            // permissionless batch down with it. Skip it.
            if (collateral == 0) continue;
            uint256 elapsed = block.timestamp - loan.interestAppliedAt;
            uint256 totalInterest = loan.interestCarry + (collateral * rate * elapsed) / WAD;
            if (totalInterest < collateral) continue;

            ILibVct(vct).applyInterest(asset, collateral, recipient);
            totalLoanedPerAsset[asset] -= loan.principal;
            if (trackLegacyTotal) legacyCollateralPerAsset[asset] -= collateral;
            carryFreed += loan.interestCarry;
            vyRouted += collateral;
            // Restores the event the deployed implementation emitted — indexers and
            // the VRO accounting both key off it.
            emit LoanEvent(
                EV_LIQUIDATED, borrower, asset, -int256(collateral),
                -int256(loan.principal), 0, collateral, 0, 0
            );
            delete book[borrower][asset];
            unchecked { ++liquidated; }
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "useLiteralContent": true
  },
  "libraries": {
    "contracts/officer/ValinityLoanLens.sol": {
      "VLOLegacyLib": "0xb6748ceb031092ccba8cc7fa3684216552aede62"
    }
  },
  "optimizer": {
    "runs": 100,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.