Skip to content
Verified contractExactBUSL-1.1

DefaultReliefLib

Address0x8f7f166d81d9964da0e7ad59507a7668ab63e5a9
Balance

0 ETH

 

Transactions

1

 

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,459,374
Creation transaction
0x4dbee1d909…68227d5b20

85 files

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

src/libraries/DefaultReliefLib.sol

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

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {DefaultManager} from "../DefaultManager.sol";
import {IDefaultManager} from "../interfaces/IDefaultManager.sol";
import {IAccrualLifecycle} from "../interfaces/IAccrualLifecycle.sol";
import {IsUSDfr} from "../interfaces/IsUSDfr.sol";
import {Config} from "./Config.sol";
import {PastDueReliefIndex} from "./PastDueReliefIndex.sol";

/// @notice Per-payment-episode relief and order-independent conservative senior valuation.
/// @dev Linked code executes in DefaultManager's proxy. The independent appended namespace
///      leaves all previous manager fields unchanged. Recorded risk uses a bounded time index;
///      virtual interest uses only the reserve's existing 100-facility native admission bound.
library DefaultReliefLib {
    using PastDueReliefIndex for PastDueReliefIndex.Book;

    /// @custom:storage-location erc7201:forestroad.storage.DefaultRelief
    struct State {
        PastDueReliefIndex.Book book;
        uint256[] nativeIds;
        mapping(uint256 id => uint256) nativeIndex;
        // Appended optimization only. Existing book fields keep their exact slots.
        // Every reuse checks the block, timestamp, weight and native cohort;
        // mark/sync/track/close invalidate after changing the indexed book.
        bytes32 cachedKey;
        uint256[5] cachedDiscounts;
    }

    /// @notice The reserve's finite native portfolio bound was violated.
    error DefaultRelief_NativeCapacity();
    /// @notice A reserve batch omitted or added a requested virtual-interest contribution.
    error DefaultRelief_InvalidAccrualBatch(uint256 expected, uint256 actual);
    /// @notice A relief index disagrees with the separately maintained gross risk carrier.
    /// @param classId The inconsistent collateral class.
    /// @param discount The indexed relief claimed for that class.
    /// @param gross The separately recorded total class risk.
    error DefaultRelief_ExceedsGross(uint256 classId, uint256 discount, uint256 gross);

    bytes32 private constant RELIEF_STORAGE_LOCATION =
        0x4b0973138cf75f3ade1481fd963d865f6007f2781863cc6d56e5905b7fa97100;

    function _state() private pure returns (State storage $) {
        assembly ("memory-safe") {
            $.slot := RELIEF_STORAGE_LOCATION
        }
    }

    /// @notice Opens a marked episode with its persistent per-loan timestamp.
    /// @param $ The calling manager's configured storage namespace.
    /// @param id The marked facility.
    /// @param classId Its immutable collateral class.
    /// @param due The authenticated payment due date.
    /// @param native Whether the loan belongs to the bound native accrual book.
    function mark(DefaultManager.DefaultStorage storage $, uint256 id, uint256 classId, uint64 due, bool native)
        public
    {
        uint256 face = $.reserves.deployedTo(id);
        DefaultManager.ReliefEpisode memory episode = $.reliefEpisode[id];
        if (due > episode.due) {
            episode = DefaultManager.ReliefEpisode(due, uint64(block.timestamp));
            $.reliefEpisode[id] = episode;
        }
        // Retained historical observable; it no longer chooses another loan's weight.
        if ($.pastDueExposure == 0 || uint256(episode.startedAt) < $.pastDueReliefAnchor) {
            $.pastDueReliefAnchor = episode.startedAt;
        }
        $.pastDueMarked[id] = true;
        $.pastDueContribution[id] = face;
        $.pastDuePrincipal[classId] += face;
        $.pastDueExposure += face;
        _state().book.open(id, classId, episode.startedAt, face);
        if (native) trackNative(id);
        _state().cachedKey = bytes32(0);
        emit IDefaultManager.PastDueMarked(id, classId, due, face);
    }

    /// @notice Reconciles one recorded contribution without enrolling an old proxy mark.
    /// @param $ The calling manager's current recorded risk carriers.
    /// @param id The facility whose recorded face changed.
    function sync(DefaultManager.DefaultStorage storage $, uint256 id) public {
        _state().book.replace(id, $.pastDueContribution[id]);
        _state().cachedKey = bytes32(0);
    }

    /// @notice Includes a legacy enrolled mark when its reserve migrates to native accrual.
    /// @param id The facility admitted to the reserve's native book.
    function trackNative(uint256 id) public {
        State storage s = _state();
        if (!s.book.episodes[id].known || s.nativeIndex[id] != 0) return;
        if (s.nativeIds.length == 100) revert DefaultRelief_NativeCapacity();
        s.nativeIds.push(id);
        s.nativeIndex[id] = s.nativeIds.length;
        s.cachedKey = bytes32(0);
    }

    /// @notice Releases recorded relief and the native-interest roster in constant time.
    /// @param id The facility leaving the marked cohort.
    function close(uint256 id) public {
        State storage s = _state();
        s.book.close(id);
        s.cachedKey = bytes32(0);
        uint256 position = s.nativeIndex[id];
        if (position == 0) return;
        uint256 lastId = s.nativeIds[s.nativeIds.length - 1];
        s.nativeIds[position - 1] = lastId;
        s.nativeIndex[lastId] = position;
        s.nativeIds.pop();
        delete s.nativeIndex[id];
    }

    /// @notice Returns total senior risk with class curator, global backstop and vault caps.
    /// @dev Junior capacity goes to past-due before declared risk as before. Within each
    ///      class, and across the shared reserve/vault bound, remaining amounts are allocated
    ///      pro-rata before applying their individual linear 21-day weights. Each division
    ///      rounds against the exiting senior. Unindexed exposure receives full weight.
    /// @param $ The calling manager's configured modules and live risk carriers.
    /// @return The total conservative senior mark, in 18-decimal USDfr units.
    function pending(DefaultManager.DefaultStorage storage $) public view returns (uint256) {
        State storage s = _state();
        uint256 reliefBps = Config.BPS - $.registry.pastDueWeightBps();
        uint256 denominator = Config.DEFAULT_REDEEM_COOLDOWN * Config.BPS;
        address reserve = address($.accrualReserve);
        uint256[5] memory cohort = _cohort(reserve);
        uint256[5] memory discounts = _discounts($, s, reserve, reliefBps, denominator, cohort);
        uint256 pastSenior;
        uint256 weightedPast;
        uint256 declaredSenior;
        for (uint256 classId = 1; classId <= Config.NUM_CLASSES; ++classId) {
            uint256 gross = $.pastDuePrincipal[classId];
            gross += cohort[classId - 1];
            uint256 declared = $.declaredDefaultedPrincipal[classId];
            if (gross == 0 && declared == 0) continue;
            uint256 discount = discounts[classId - 1];
            if (discount > gross) revert DefaultRelief_ExceedsGross(classId, discount, gross);
            uint256 pool = $.curator.poolBalance(classId);
            uint256 residual = gross > pool ? gross - pool : 0;
            pastSenior += residual;
            if (residual != 0) weightedPast += Math.mulDiv(gross - discount, residual, gross, Math.Rounding.Ceil);
            uint256 available = pool > gross ? pool - gross : 0;
            if (declared > available) declaredSenior += declared - available;
        }
        uint256 coverage = address($.backstop) == address(0) ? 0 : $.backstop.coverageReserve();
        uint256 pastAfter = pastSenior > coverage ? pastSenior - coverage : 0;
        coverage = coverage > pastSenior ? coverage - pastSenior : 0;
        declaredSenior = declaredSenior > coverage ? declaredSenior - coverage : 0;
        if (pastAfter == 0) return declaredSenior;
        weightedPast = Math.mulDiv(weightedPast, pastAfter, pastSenior, Math.Rounding.Ceil);
        uint256 assets = IsUSDfr($.vault).totalAssets();
        uint256 executable = assets > declaredSenior ? assets - declaredSenior : 0;
        return
            declaredSenior + Math.mulDiv(weightedPast, Math.min(pastAfter, executable), pastAfter, Math.Rounding.Ceil);
    }

    /// @notice Primes a disposable pricing optimization with exact, current discounts.
    /// @dev No caller supplies values. A view checks the block, timestamp, reserve cohort
    ///      and weight; every indexed-book change invalidates the key. Junior capacity and
    ///      vault assets are never cached. Posting a marked loan invalidates synchronously.
    /// @param $ The manager's configured modules and live risk carriers.
    function prepare(DefaultManager.DefaultStorage storage $) public {
        State storage s = _state();
        if (s.nativeIds.length == 0 && $.pastDueExposure == 0) return;
        uint256 reliefBps = Config.BPS - $.registry.pastDueWeightBps();
        address reserve = address($.accrualReserve);
        uint256[5] memory cohort = _cohort(reserve);
        bytes32 key = _cacheKey(reserve, reliefBps, cohort);
        if (s.cachedKey == key) return;
        s.cachedDiscounts =
            _computeDiscounts($, s, reserve, reliefBps, Config.DEFAULT_REDEEM_COOLDOWN * Config.BPS, cohort);
        s.cachedKey = key;
    }

    function _cohort(address reserve) private view returns (uint256[5] memory cohort) {
        if (reserve != address(0)) {
            for (uint256 classId = 1; classId <= Config.NUM_CLASSES; ++classId) {
                cohort[classId - 1] = IAccrualLifecycle(reserve).accruedPastDue(classId);
            }
        }
    }

    function _cacheKey(address reserve, uint256 reliefBps, uint256[5] memory cohort) private view returns (bytes32) {
        // Posting any marked loan invalidates the book cache synchronously in sync().
        // Between such callbacks individual earned amounts can only increase. The
        // class totals therefore bind their distribution at this block's timestamp,
        // without invalidating on an unrelated, unmarked loan's preparation.
        return keccak256(abi.encode(block.chainid, block.number, block.timestamp, reserve, reliefBps, cohort));
    }

    function _discounts(
        DefaultManager.DefaultStorage storage $,
        State storage s,
        address reserve,
        uint256 reliefBps,
        uint256 denominator,
        uint256[5] memory cohort
    ) private view returns (uint256[5] memory discounts) {
        if (s.cachedKey != bytes32(0) && s.cachedKey == _cacheKey(reserve, reliefBps, cohort)) return s.cachedDiscounts;
        return _computeDiscounts($, s, reserve, reliefBps, denominator, cohort);
    }

    function _computeDiscounts(
        DefaultManager.DefaultStorage storage $,
        State storage s,
        address reserve,
        uint256 reliefBps,
        uint256 denominator,
        uint256[5] memory cohort
    ) private view returns (uint256[5] memory discounts) {
        uint256[5] memory remainders;
        (discounts, remainders) = _virtualDiscounts(s, reserve, reliefBps, denominator);
        if (reliefBps == 0) return discounts;
        for (uint256 classId = 1; classId <= Config.NUM_CLASSES; ++classId) {
            // Preserve the original pending() fast path. A class with no past-due
            // gross has no indexed discount to read, even when it has declared loss.
            if ($.pastDuePrincipal[classId] == 0 && cohort[classId - 1] == 0) continue;
            uint256 secondsFace = s.book.reliefSeconds(classId);
            discounts[classId - 1] += Math.mulDiv(secondsFace, reliefBps, denominator);
            discounts[classId - 1] +=
                (remainders[classId - 1] + mulmod(secondsFace, reliefBps, denominator)) / denominator;
        }
    }

    /// @dev QX-01: one bounded reserve read replaces one external call per native mark.
    ///      All loans share exactly the same frontier; class allocation and rational remainders
    ///      are unchanged. Discount reuse is separately bound to the current cohort and book.
    function _virtualDiscounts(State storage s, address reserve, uint256 reliefBps, uint256 denominator)
        private
        view
        returns (uint256[5] memory discounts, uint256[5] memory remainders)
    {
        if (reliefBps == 0) return (discounts, remainders);
        uint256 length = s.nativeIds.length;
        uint256[] memory ids = new uint256[](length);
        uint256[] memory secondsBps = new uint256[](length);
        uint256[] memory classes = new uint256[](length);
        uint256 count;
        for (uint256 i; i < length; ++i) {
            uint256 id = s.nativeIds[i];
            uint256 remaining = s.book.remaining(id);
            if (remaining == 0) continue;
            ids[count] = id;
            secondsBps[count] = remaining * reliefBps;
            classes[count++] = s.book.episodes[id].classId - 1;
        }
        if (count == 0) return (discounts, remainders);
        assembly ("memory-safe") {
            mstore(ids, count)
        }
        uint256[] memory amounts = IAccrualLifecycle(reserve).unpostedAccruedLoans(ids);
        if (amounts.length != count) revert DefaultRelief_InvalidAccrualBatch(count, amounts.length);
        for (uint256 i; i < count; ++i) {
            uint256 classIndex = classes[i];
            discounts[classIndex] += Math.mulDiv(amounts[i], secondsBps[i], denominator);
            remainders[classIndex] += mulmod(amounts[i], secondsBps[i], denominator);
        }
    }
}
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.