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.solmain13.45 KB
- lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol8.33 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol9.28 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol6.57 KB
- lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol12.13 KB
- lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/ERC4626Upgradeable.sol13.29 KB
- lib/openzeppelin-contracts-upgradeable/contracts/token/ERC721/ERC721Upgradeable.sol17.8 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol1.19 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol3.66 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol4.51 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol1.15 KB
- lib/openzeppelin-contracts/contracts/access/IAccessControl.sol3.34 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol193 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol637 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol182 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol12.18 KB
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol882 B
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol6.54 KB
- lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol6.24 KB
- lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol473 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol10.08 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol4.93 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol997 B
- lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Metadata.sol792 B
- lib/openzeppelin-contracts/contracts/token/ERC721/utils/ERC721Utils.sol1.92 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6 KB
- lib/openzeppelin-contracts/contracts/utils/Errors.sol896 B
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4.18 KB
- lib/openzeppelin-contracts/contracts/utils/Strings.sol19.28 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol32.15 KB
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol2.61 KB
- lib/solady/src/utils/FixedPointMathLib.sol55.69 KB
- src/ClaimBridge.sol50.08 KB
- src/CommitmentLedger.sol13.84 KB
- src/CommitmentLedgerFactory.sol814 B
- src/ConservativeImpairmentMath.sol23.87 KB
- src/DefaultManager.sol78.21 KB
- src/WaterfallEngine.sol87.97 KB
- src/interfaces/IAccrualExposure.sol2.49 KB
- src/interfaces/IAccrualLifecycle.sol6.67 KB
- src/interfaces/IAccrualMigration.sol2.22 KB
- src/interfaces/IAttestationOracle.sol11.8 KB
- src/interfaces/ICascadeBackstop.sol3.47 KB
- src/interfaces/ICollateralRegistry.sol21.89 KB
- src/interfaces/ICommitmentLedger.sol3.25 KB
- src/interfaces/ICommitmentPrincipalSource.sol188 B
- src/interfaces/IComplianceRegistry.sol2.52 KB
- src/interfaces/IConservativeImpairmentBook.sol3.16 KB
- src/interfaces/IContinuousAccrual.sol4.69 KB
- src/interfaces/ICuratorModule.sol21.74 KB
- src/interfaces/IDefaultManager.sol34.39 KB
- src/interfaces/IImpairmentSource.sol2.26 KB
- src/interfaces/ILossProtection.sol355 B
- src/interfaces/IMintRedeemController.sol42.91 KB
- src/interfaces/IPointsModule.sol2.43 KB
- src/interfaces/IReserveLossAbsorber.sol2.11 KB
- src/interfaces/IReserveManager.sol31.28 KB
- src/interfaces/IRevisionedImpairmentSource.sol2.79 KB
- src/interfaces/IWaterfallEngine.sol16.65 KB
- src/interfaces/IsUSDfr.sol14.06 KB
- src/libraries/AccrualMath.sol8.76 KB
- src/libraries/BridgeAccrualLib.sol5.25 KB
- src/libraries/BridgeFundingLib.sol14.58 KB
- src/libraries/BridgeMixedInterestLib.sol32.77 KB
- src/libraries/Config.sol23.1 KB
- src/libraries/DefaultAccrualLib.sol38.7 KB
- src/libraries/DefaultBackstopLib.sol4.39 KB
- src/libraries/DefaultInitLib.sol5.62 KB
- src/libraries/DefaultLossLib.sol24.38 KB
- src/libraries/LossEventIds.sol1.35 KB
- src/libraries/LossProtectionLib.sol5.39 KB
- src/libraries/PastDueReliefIndex.sol6.08 KB
- src/libraries/PointsHookGas.sol2.73 KB
- src/libraries/Roles.sol4.2 KB
- src/libraries/VaultAccrualLib.sol18.03 KB
- src/libraries/VaultFeeMath.sol9.97 KB
- src/libraries/VaultStreamLib.sol4.99 KB
- src/libraries/WaterfallAccrualLib.sol14.98 KB
- src/sUSDfr.sol70.36 KB
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.