Skip to content
Verified contractExactBUSL-1.1

ReserveAccrualLifecycleLib

Address0xea8ad02088f5ace6bd57abfea167475b38af8ff3
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 100 runs
EVM version
cancun
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,486,052
Creation transaction
0x020e996d67…1bfba1ac0c

93 files

The source code is large: one file is shown at a time. Choose a file in the list.

src/libraries/ReserveAccrualLifecycleLib.sol

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

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

import {ClaimBridge} from "../ClaimBridge.sol";
import {ICollateralRegistry} from "../interfaces/ICollateralRegistry.sol";
import {IAccrualLifecycle, IAccrualRegistry, IAccrualRisk, IAccrualBridge} from "../interfaces/IAccrualLifecycle.sol";
import {AccrualBook} from "./AccrualBook.sol";
import {AccrualLoans} from "./AccrualLoans.sol";
import {AccrualCeiling} from "./AccrualCeiling.sol";
import {ReserveAccrualLib} from "./ReserveAccrualLib.sol";
import {ReserveRoundingLib} from "./ReserveRoundingLib.sol";
import {ReserveAccrualStorageLib} from "./ReserveAccrualStorageLib.sol";
import {ReserveStorageLib} from "./ReserveStorageLib.sol";
import {ReserveCreditLib} from "./ReserveCreditLib.sol";

/// @title ReserveAccrualLifecycleLib
/// @notice Receipt, amendment, default-stop and terminal accounting for continuously accrued loans.
/// @dev Split from ReserveAccrualCreditLib so both deployable linked libraries retain material
///      EIP-170 margin. Public methods execute by delegatecall in ReserveManager's context.
library ReserveAccrualLifecycleLib {
    using AccrualBook for AccrualBook.Book;
    using AccrualLoans for AccrualLoans.State;
    using ReserveStorageLib for ReserveManager.ReserveStorage;

    uint256 internal constant MAX_EXPOSURE = type(uint256).max / 10_000;

    error AccrualCredit_WrongCaller(address expected, address caller);
    error AccrualCredit_UnsupportedTerms(uint256 facilityId);
    error AccrualCredit_Unknown(uint256 facilityId);
    error AccrualCredit_ExposureCapacity();
    error AccrualCredit_UnpostedRisk(uint256 facilityId);
    error AccrualCredit_ReceiptMismatch(uint256 facilityId);
    error AccrualCredit_InvalidWriteDown(uint256 facilityId);

    event AccruedLoanPosted(uint256 indexed facilityId, address indexed asset, uint256 amount, uint256 faceAfter);
    event AccrualLoanAligned(
        uint256 indexed facilityId,
        uint64 indexed closureNonce,
        uint64 at,
        uint256 positiveCorrection,
        uint256 roundingLoss,
        bool stopped
    );
    event AccrualPastDueSet(uint256 indexed facilityId, bool marked);
    event AccrualCeilingReserved(uint256 indexed facilityId, uint256 previousCeiling, uint256 nextCeiling);

    /// @notice Matches both signed receipt legs against debt, then measures the exact native cash arrival.
    function repay(
        ReserveManager.ReserveStorage storage native,
        uint256 id,
        address payer,
        uint256 principal,
        uint256 interest
    ) public returns (uint256 outstanding) {
        ReserveAccrualStorageLib.State storage s = _fresh();
        _caller(s.modules.waterfall);
        _identity(s, id);
        ReserveRoundingLib.prepare(native, id);
        s.busy = true;
        AccrualLoans.LifecycleWork memory work =
            s.loans.repay(id, principal, interest, ReserveAccrualStorageLib.now64());
        _aligned(native, s, work);
        uint256 total = principal + interest;
        uint256 scale = s.loans.loans[id].terms.scale;
        uint256 received = ReserveCreditLib.payAccrued(
            native, id, payer, total / scale, work.principalReduction, work.interestReduction
        );
        if (received != total) revert AccrualCredit_ReceiptMismatch(id);
        s.recordedFace -= total;
        outstanding = native.deployed[id];
        if (outstanding != s.loans.loans[id].principal + s.loans.loans[id].unpaidInterest) {
            revert AccrualCredit_ReceiptMismatch(id);
        }
        // A maturity checkpoint stops the curve without marking the loan permanently stopped.
        // Keep its ceiling on the remaining face so a later partial receipt cannot recreate
        // reserved capacity for interest that the closed curve can never earn.
        if (work.stopped || s.loans.loans[id].permanentlyStopped) _replaceCeiling(s, id, outstanding);
        _syncDormantPikDue(s, id, work);
        s.busy = false;
    }

    /// @dev Closing a dormant curve can service a signed PIK boundary before applying
    ///      the receipt. Commit that same clock advance only after cash/debt reconciliation;
    ///      a callback failure rolls the entire receipt back. Mixed clocks accept terminal
    ///      zero without touching their cash date. A pure PIK clock exposes legal maturity
    ///      as its final balloon and must never receive the coordinator's zero sentinel.
    function _syncDormantPikDue(
        ReserveAccrualStorageLib.State storage s,
        uint256 id,
        AccrualLoans.LifecycleWork memory work
    ) private {
        if (work.previousDue == 0) return;
        AccrualLoans.Loan storage loan = s.loans.loans[id];
        if (loan.mixed) {
            IAccrualBridge(s.modules.bridge).setAccruedPaymentDue(id, work.nextDue);
        } else {
            uint64 nextDue = work.nextDue == 0 ? loan.legalMaturity : work.nextDue;
            if (nextDue > ClaimBridge(s.modules.bridge).facility(id).nextPaymentDue) {
                IAccrualBridge(s.modules.bridge).setAccruedPaymentDue(id, nextDue);
            }
        }
    }

    /// @notice Completes retirement only after the native face, bridge state and risk hooks have closed.
    function retire(ReserveManager.ReserveStorage storage native, uint256 id) public {
        ReserveAccrualStorageLib.State storage s = _fresh();
        if (msg.sender != s.modules.waterfall && msg.sender != s.modules.defaultManager) {
            revert AccrualCredit_WrongCaller(s.modules.waterfall, msg.sender);
        }
        _identity(s, id);
        ClaimBridge.LoanState state = ClaimBridge(s.modules.bridge).facility(id).state;
        if (
            native.deployed[id] != 0
                || (state != ClaimBridge.LoanState.Repaid && state != ClaimBridge.LoanState.Resolved)
        ) {
            revert AccrualCredit_ReceiptMismatch(id);
        }
        s.loans.retire(id, ReserveAccrualStorageLib.now64());
        _replaceCeiling(s, id, 0);
    }

    /// @notice Synchronizes a native declared-loss face reduction without treating it as a receipt.
    function writeDown(uint256 id, uint256 amount) public {
        ReserveAccrualStorageLib.State storage s = _fresh();
        _caller(s.modules.defaultManager);
        _identity(s, id);
        AccrualLoans.Loan storage loan = s.loans.loans[id];
        uint256 face = loan.principal + loan.unpaidInterest;
        if (!loan.permanentlyStopped || amount > face || ReserveAccrualStorageLib.facilityUnposted(id) != 0) {
            revert AccrualCredit_InvalidWriteDown(id);
        }
        uint256 principal = amount < loan.principal ? amount : loan.principal;
        loan.principal -= principal;
        loan.unpaidInterest -= amount - principal;
        // A mixed loss consumes uncapitalized PIK before cash interest. Preserve the subset
        // identity even when the cascade reaches the interest layer.
        if (loan.mixed && loan.unpaidCashInterest > loan.unpaidInterest) {
            loan.unpaidCashInterest = loan.unpaidInterest;
        }
        s.recordedFace -= amount;
        _replaceCeiling(s, id, face - amount);
    }

    /// @notice Replaces only future terms after the bridge consumes its exact signed amendment.
    function amend(ReserveManager.ReserveStorage storage native, uint256 id, IAccrualLifecycle.Terms memory terms)
        public
    {
        ReserveAccrualStorageLib.State storage s = _fresh();
        _caller(s.modules.bridge);
        _identity(s, id);
        AccrualLoans.Loan storage loan = s.loans.loans[id];
        if (terms.yearSeconds != 360 days && (loan.pik || terms.yearSeconds != 365 days)) {
            revert AccrualCredit_UnsupportedTerms(id);
        }
        uint64 at = ReserveAccrualStorageLib.now64();
        (uint256 principal, uint256 interest,) = s.loans.loanFace(id, at);
        AccrualCeiling.Terms memory remaining;
        remaining.face = principal + interest;
        remaining.frozenBasis = !loan.pik
            ? principal
            : (loan.nextCapitalization != 0 && loan.nextCapitalization <= at ? remaining.face : loan.frozenPikBasis);
        remaining.scale = loan.terms.scale;
        remaining.yearSeconds = terms.yearSeconds;
        remaining.rateBps = terms.rateBps;
        remaining.at = at;
        remaining.nextCapitalization = terms.nextPaymentDue;
        remaining.paymentInterval = terms.paymentInterval;
        remaining.maturity = terms.maturity;
        uint256 ceiling = ReserveAccrualLib.loanCeiling(remaining, loan.pik);
        _replaceCeiling(s, id, ceiling);
        ReserveRoundingLib.prepare(native, id);
        s.busy = true;
        AccrualLoans.LifecycleWork memory work = s.loans.amend(
            id,
            AccrualLoans.Amendment({
                balanceCeiling: ceiling,
                yearSeconds: terms.yearSeconds,
                rateBps: terms.rateBps,
                nextPaymentDue: terms.nextPaymentDue,
                paymentInterval: terms.paymentInterval,
                maturity: terms.maturity
            }),
            at
        );
        _aligned(native, s, work);
        s.busy = false;
    }

    /// @notice Replaces both future rates and the signed PIK schedule after exact bridge attestation.
    function amendMixed(
        ReserveManager.ReserveStorage storage native,
        uint256 id,
        IAccrualLifecycle.MixedTerms memory terms
    ) public {
        ReserveAccrualStorageLib.State storage s = _fresh();
        _caller(s.modules.bridge);
        _identity(s, id);
        uint256 combinedRate = uint256(terms.cashRateBps) + terms.pikRateBps;
        if (terms.yearSeconds != 360 days || terms.cashRateBps == 0 || terms.pikRateBps == 0 || combinedRate > 10_000) {
            revert AccrualCredit_UnsupportedTerms(id);
        }
        AccrualLoans.Loan storage loan = s.loans.loans[id];
        uint64 at = ReserveAccrualStorageLib.now64();
        (uint256 principal, uint256 interest,) = s.loans.loanFace(id, at);
        uint256 face = principal + interest;
        // A principal receipt rebases only the cash curve. Until the next signed PIK
        // capitalization the PIK curve can therefore retain a basis above current face.
        // Replacing capacity from face alone would clip that already-signed coupon.
        principal = face > loan.frozenPikBasis ? face : loan.frozenPikBasis;
        uint256 ceiling = ReserveAccrualLib.loanCeiling(
            AccrualCeiling.Terms({
                face: face,
                frozenBasis: principal,
                scale: loan.terms.scale,
                yearSeconds: terms.yearSeconds,
                rateBps: uint16(combinedRate),
                at: at,
                nextCapitalization: terms.nextPikCapitalization,
                paymentInterval: terms.pikCapitalizationInterval,
                maturity: terms.maturity
            }),
            true
        );
        _replaceCeiling(s, id, ceiling);
        ReserveRoundingLib.prepare(native, id);
        s.busy = true;
        AccrualLoans.LifecycleWork memory work = s.loans.amendMixed(
            id,
            AccrualLoans.MixedAmendment({
                pikTerms: AccrualLoans.Amendment({
                    balanceCeiling: ceiling,
                    yearSeconds: terms.yearSeconds,
                    rateBps: terms.pikRateBps,
                    nextPaymentDue: terms.nextPikCapitalization,
                    paymentInterval: terms.pikCapitalizationInterval,
                    maturity: terms.maturity
                }),
                cashRateBps: terms.cashRateBps
            }),
            at
        );
        _aligned(native, s, work);
        s.busy = false;
    }

    /// @notice Stops at declaration and posts the full earned claim before any default snapshot.
    function stop(ReserveManager.ReserveStorage storage native, uint256 id) public {
        ReserveAccrualStorageLib.State storage s = _fresh();
        _caller(s.modules.defaultManager);
        _identity(s, id);
        ReserveRoundingLib.prepare(native, id);
        s.busy = true;
        AccrualLoans.LifecycleWork memory work = s.loans.stop(id, ReserveAccrualStorageLib.now64());
        _aligned(native, s, work);
        _replaceCeiling(s, id, native.deployed[id]);
        s.busy = false;
    }

    /// @notice Sets a cohort only after posting its initial marked face, preventing double counting.
    function setPastDue(uint256 id, bool marked) public {
        ReserveAccrualStorageLib.State storage s = _fresh();
        _caller(s.modules.defaultManager);
        _identity(s, id);
        if (marked && ReserveAccrualStorageLib.facilityUnposted(id) != 0) revert AccrualCredit_UnpostedRisk(id);
        s.loans.book.setPastDue(id, marked, ReserveAccrualStorageLib.now64());
        emit AccrualPastDueSet(id, marked);
    }

    function _aligned(
        ReserveManager.ReserveStorage storage native,
        ReserveAccrualStorageLib.State storage s,
        AccrualLoans.LifecycleWork memory work
    ) private {
        _post(native, s, work.facilityId, work.posting);
        if (work.roundingLoss != 0) ReserveRoundingLib.allocate(native, work);
        emit AccrualLoanAligned(
            work.facilityId, work.closureNonce, work.at, work.positiveCorrection, work.roundingLoss, work.stopped
        );
    }

    function _post(
        ReserveManager.ReserveStorage storage native,
        ReserveAccrualStorageLib.State storage s,
        uint256 id,
        uint256 amount
    ) private {
        if (amount == 0) return;
        ReserveAccrualStorageLib.Identity storage identity = s.identities[id];
        native.deployed[id] += amount;
        native.totalDeployedPrincipal += amount;
        s.recordedFace += amount;
        IAccrualRegistry(s.modules.registry).recordAccruedExposure(
            identity.classId, identity.borrowerId, identity.stateId, amount
        );
        if (s.loans.book.entries[id].pastDue) IAccrualRisk(s.modules.defaultManager).onAccrualPosted(id, amount);
        emit AccruedLoanPosted(id, identity.asset, amount, native.deployed[id]);
    }

    function _admitAdditional(ReserveAccrualStorageLib.State storage s, uint256 additional) private view {
        uint256 effective = ICollateralRegistry(s.modules.registry).totalBookExposure();
        uint256 future = _reservedExposure(s);
        if (
            effective > MAX_EXPOSURE || future > MAX_EXPOSURE - effective
                || additional > MAX_EXPOSURE - effective - future
        ) revert AccrualCredit_ExposureCapacity();
    }

    function _reservedExposure(ReserveAccrualStorageLib.State storage s) private view returns (uint256 amount) {
        uint256 effectiveFace = s.recordedFace + ReserveAccrualStorageLib.unposted();
        return s.reservedCeilings > effectiveFace ? s.reservedCeilings - effectiveFace : 0;
    }

    function _replaceCeiling(ReserveAccrualStorageLib.State storage s, uint256 id, uint256 next) private {
        uint256 previous = s.identities[id].reservedCeiling;
        if (next > previous) _admitAdditional(s, next - previous);
        s.reservedCeilings = s.reservedCeilings - previous + next;
        s.identities[id].reservedCeiling = next;
        emit AccrualCeilingReserved(id, previous, next);
    }

    function _fresh() private view returns (ReserveAccrualStorageLib.State storage s) {
        ReserveAccrualLib.requireFresh();
        s = ReserveAccrualStorageLib.state();
        if (!s.enabled) revert ReserveAccrualLib.ReserveAccrual_NotEnabled();
    }

    function _identity(ReserveAccrualStorageLib.State storage s, uint256 id) private view {
        if (!s.identities[id].known) revert AccrualCredit_Unknown(id);
    }

    function _caller(address expected) private view {
        if (msg.sender != expected) revert AccrualCredit_WrongCaller(expected, msg.sender);
    }
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 100,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "solady/=lib/solady/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.