Verified contractExactBUSL-1.1
CommitmentLedgerFactory
Address0xc91716664e660bd44a244937ecec80f48e175166
- 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,080
- Creation transaction
- 0xcb6d8f11c0…996614a957
9 files
- src/CommitmentLedgerFactory.solmain814 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- src/CommitmentLedger.sol13.84 KB
- src/interfaces/ICascadeBackstop.sol3.47 KB
- src/interfaces/ICommitmentLedger.sol3.25 KB
- src/interfaces/IConservativeImpairmentBook.sol3.16 KB
- src/interfaces/ICuratorModule.sol22.46 KB
- src/libraries/Config.sol23.1 KB
src/CommitmentLedgerFactory.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
import {CommitmentLedger} from "./CommitmentLedger.sol";
/// @title CommitmentLedgerFactory
/// @notice Keeps the per-manager ledger deployment out of the UUPS implementation's runtime
/// bytecode. The factory is deployed by `DefaultManager`'s implementation constructor;
/// each proxy initialization then creates a ledger owned by that proxy.
/// @dev Anyone may request a ledger for an address. A ledger has no funds and accepts state writes
/// only from its immutable manager, so permissionless factory use cannot affect a protocol
/// instance.
contract CommitmentLedgerFactory {
function create(address manager) external returns (CommitmentLedger ledger) {
ledger = new CommitmentLedger(manager);
}
}
lib/openzeppelin-contracts/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);
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
src/CommitmentLedger.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
import {ICommitmentLedger} from "./interfaces/ICommitmentLedger.sol";
import {ICascadeBackstop} from "./interfaces/ICascadeBackstop.sol";
import {IConservativeImpairmentBook} from "./interfaces/IConservativeImpairmentBook.sol";
import {ICuratorModule} from "./interfaces/ICuratorModule.sol";
import {Config} from "./libraries/Config.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title CommitmentLedger — live-event principal and conservative residual accounting
/// @notice Per-class principal totals price declared defaults in constant time. Curator pools
/// cover their own classes after past-due demand; the shared reserve covers the remainder.
/// @dev The manager is the proxy that deploys this module during initialization. Keeping the
/// ledger behind a separate contract leaves the DefaultManager implementation below EIP-170
/// while preserving the manager's existing ERC-7201 layout as an append-only address tail.
contract CommitmentLedger is ICommitmentLedger {
bytes32 private constant COMMITMENT_LEDGER_STORAGE_LOCATION =
0x4284dece5550b2153beac9968b0c4d027165d14c7409a89f67ea4baed9160d00;
error CommitmentLedger_ZeroManager();
error CommitmentLedger_NotManager(address caller);
error CommitmentLedger_AlreadyRegistered(uint256 eventId);
error CommitmentLedger_UnknownEvent(uint256 eventId);
error CommitmentLedger_InvalidClass(uint256 classId);
error DefaultManager_BackstopContractViolated(uint256 residual, uint256 covered, uint256 received);
error CommitmentLedger_DirectCall();
struct Entry {
// W6 storage compatibility: these three words are already baselined. Under ADR-0035,
// `remainingCoverage` is the event's remaining-principal claim bound, not a snapshotted
// coverage ceiling; the shared reserve is applied separately when pricing residuals.
uint256 remainingCoverage;
uint256 remainingPrincipal;
uint256 consumed;
}
/// @inheritdoc ICommitmentLedger
function register(uint256 eventId, uint256 classId, uint256 remainingPrincipal) external onlyManager {
if (classId == 0 || classId > Config.NUM_CLASSES) revert CommitmentLedger_InvalidClass(classId);
CommitmentLedgerStorage storage $ = _storage();
if ($.eventIndexPlusOne[eventId] != 0) revert CommitmentLedger_AlreadyRegistered(eventId);
$.eventIds.push(eventId);
$.eventIndexPlusOne[eventId] = $.eventIds.length;
$.eventMetadata[eventId] = uint8(classId);
_setPrincipal($, eventId, remainingPrincipal);
emit CommitmentRegistered(eventId, classId, remainingPrincipal);
}
/// @inheritdoc ICommitmentLedger
function updatePrincipal(uint256 eventId, uint256 remainingPrincipal) external onlyManager {
CommitmentLedgerStorage storage $ = _storage();
if ($.eventIndexPlusOne[eventId] == 0) revert CommitmentLedger_UnknownEvent(eventId);
Entry storage entry = $.entries[eventId];
uint256 oldDeliverable = _min(entry.remainingCoverage, entry.remainingPrincipal);
uint256 newDeliverable = _min(entry.remainingCoverage, remainingPrincipal);
$.aggregateDeliverable = $.aggregateDeliverable - oldDeliverable + newDeliverable;
_setPrincipal($, eventId, remainingPrincipal);
emit CommitmentPrincipalUpdated(eventId, remainingPrincipal);
}
/// @custom:storage-location erc7201:forestroad.storage.CommitmentLedger
struct CommitmentLedgerStorage {
mapping(uint256 eventId => Entry) entries;
uint256[] eventIds;
mapping(uint256 eventId => uint256) eventIndexPlusOne;
uint256 aggregateDeliverable;
uint256 aggregateRemaining;
uint256 aggregateConsumed;
// W7 tail append: class plus drawn flag for declaration-time rows.
mapping(uint256 eventId => uint8) eventMetadata;
// Per-class remaining principal, appended without moving any existing ledger field.
mapping(uint256 classId => uint256) remainingPrincipalByClass;
}
struct ResidualState {
uint256 pastDueGross;
uint256 pastDueResidual;
uint256 gross;
uint256 reserve;
uint256 pastDueLayerTwo;
address backstop;
uint256 declaredCurator;
uint256 declaredResidual;
}
address public immutable manager;
uint8 private constant DRAWN_FLAG = 1 << 7;
uint8 private constant CLASS_MASK = DRAWN_FLAG - 1;
constructor(address manager_) {
if (manager_ == address(0)) revert CommitmentLedger_ZeroManager();
manager = manager_;
}
modifier onlyManager() {
if (msg.sender != manager) revert CommitmentLedger_NotManager(msg.sender);
_;
}
/// @inheritdoc ICommitmentLedger
/// @dev Called by DefaultManager with `delegatecall`, so SGrove sees the manager as its
/// caller and sends the asset directly to the manager. A direct call cannot impersonate
/// that context because the immutable manager differs from `address(this)`.
function coverDelegate(address backstop, address asset, uint256 eventId, uint256 residual)
external
returns (uint256 covered)
{
if (address(this) != manager) revert CommitmentLedger_DirectCall();
if (residual == 0 || backstop == address(0)) return 0;
IERC20 token = IERC20(asset);
uint256 before = token.balanceOf(address(this));
covered = ICascadeBackstop(backstop).coverShortfall(eventId, residual);
uint256 received = token.balanceOf(address(this)) - before;
if (covered > residual || received != covered) {
revert DefaultManager_BackstopContractViolated(residual, covered, received);
}
}
/// @inheritdoc ICommitmentLedger
function sync(uint256 eventId, uint256 remainingCoverage, uint256 remainingPrincipal, uint256 covered)
external
onlyManager
returns (bool firstDraw)
{
return _sync(_storage(), eventId, remainingCoverage, remainingPrincipal, covered);
}
function _sync(
CommitmentLedgerStorage storage $,
uint256 eventId,
uint256 remainingCoverage,
uint256 remainingPrincipal,
uint256 covered
) private returns (bool firstDraw) {
if (covered == 0) return false;
if ($.eventIndexPlusOne[eventId] == 0) revert CommitmentLedger_UnknownEvent(eventId);
Entry storage entry = $.entries[eventId];
firstDraw = $.eventMetadata[eventId] & DRAWN_FLAG == 0;
uint256 oldDeliverable = _min(entry.remainingCoverage, entry.remainingPrincipal);
uint256 newDeliverable = _min(remainingCoverage, remainingPrincipal);
$.aggregateDeliverable = $.aggregateDeliverable - oldDeliverable + newDeliverable;
$.aggregateRemaining = $.aggregateRemaining - entry.remainingCoverage + remainingCoverage;
$.eventMetadata[eventId] |= DRAWN_FLAG;
entry.consumed += covered;
$.aggregateConsumed += covered;
entry.remainingCoverage = remainingCoverage;
_setPrincipal($, eventId, remainingPrincipal);
emit CommitmentSynced(eventId, remainingCoverage, remainingPrincipal, newDeliverable, $.aggregateDeliverable);
}
/// @inheritdoc ICommitmentLedger
function release(uint256 eventId) external onlyManager {
CommitmentLedgerStorage storage $ = _storage();
Entry storage entry = $.entries[eventId];
uint256 indexPlusOne = $.eventIndexPlusOne[eventId];
if (indexPlusOne == 0) return;
uint256 released = _min(entry.remainingCoverage, entry.remainingPrincipal);
_setPrincipal($, eventId, 0);
$.aggregateDeliverable -= released;
$.aggregateRemaining -= entry.remainingCoverage;
$.aggregateConsumed -= entry.consumed;
uint256 index = indexPlusOne - 1;
uint256 length = $.eventIds.length;
// Preserve the existing eventAt enumeration order when a live row is removed.
// Residual reads use per-class totals and never walk this array.
for (uint256 i = index; i + 1 < length; ++i) {
uint256 shiftedId = $.eventIds[i + 1];
$.eventIds[i] = shiftedId;
$.eventIndexPlusOne[shiftedId] = i + 1;
}
$.eventIds.pop();
delete $.eventIndexPlusOne[eventId];
delete $.eventMetadata[eventId];
delete $.entries[eventId];
emit CommitmentReleased(eventId, released, $.aggregateDeliverable);
}
/// @inheritdoc ICommitmentLedger
function deliverableAggregate() external view returns (uint256) {
return _storage().aggregateDeliverable;
}
/// @inheritdoc ICommitmentLedger
function conservativeResiduals() external view returns (uint256 residual, uint256 pastDueSenior) {
CommitmentLedgerStorage storage $ = _storage();
IConservativeImpairmentBook source = IConservativeImpairmentBook(manager);
(,,,, address curatorAddress,,,) = source.modules();
ResidualState memory s;
for (uint256 i = 0; i < Config.NUM_CLASSES; ++i) {
uint256 classId = i + 1;
uint256 pastDue = source.pastDuePrincipal(classId);
uint256 pool = curatorAddress == address(0) ? 0 : ICuratorModule(curatorAddress).poolBalance(classId);
uint256 curatorForPastDue = _min(pastDue, pool);
s.pastDueGross += pastDue;
s.pastDueResidual += pastDue - curatorForPastDue;
uint256 principal = $.remainingPrincipalByClass[classId];
uint256 curatorForDeclared = _min(principal, pool - curatorForPastDue);
s.gross += principal;
s.declaredCurator += curatorForDeclared;
s.declaredResidual += principal - curatorForDeclared;
}
s.gross += s.pastDueGross;
if (s.gross == 0) return (0, 0);
s.backstop = source.backstop();
if (s.backstop != address(0)) {
s.reserve = ICascadeBackstop(s.backstop).coverageReserve();
if (s.pastDueResidual != 0 && s.reserve != 0) {
s.pastDueLayerTwo = _min(s.pastDueResidual, s.reserve);
s.reserve -= s.pastDueLayerTwo;
}
}
uint256 declaredJunior = s.declaredCurator + _min(s.declaredResidual, s.reserve);
uint256 pastDueJunior = s.pastDueGross - s.pastDueResidual + s.pastDueLayerTwo;
residual = s.gross - pastDueJunior - declaredJunior;
pastDueSenior = s.pastDueResidual - s.pastDueLayerTwo;
}
function remainingAggregate() external view returns (uint256) {
return _storage().aggregateRemaining;
}
function consumed(uint256 eventId) external view returns (uint256) {
return _storage().entries[eventId].consumed;
}
function consumedAggregate() external view returns (uint256) {
return _storage().aggregateConsumed;
}
/// @inheritdoc ICommitmentLedger
function deliverable(uint256 eventId) external view returns (uint256) {
Entry memory entry = _storage().entries[eventId];
return _min(entry.remainingCoverage, entry.remainingPrincipal);
}
/// @inheritdoc ICommitmentLedger
function state(uint256 eventId)
external
view
returns (uint256 remainingCoverage, uint256 remainingPrincipal, uint256 eventDeliverable)
{
Entry memory entry = _storage().entries[eventId];
remainingPrincipal = entry.remainingPrincipal;
return (entry.remainingCoverage, remainingPrincipal, _min(entry.remainingCoverage, remainingPrincipal));
}
function eventCount() external view returns (uint256) {
return _storage().eventIds.length;
}
function eventAt(uint256 index) external view returns (uint256 eventId) {
return _storage().eventIds[index];
}
/// @inheritdoc ICommitmentLedger
function eventInfo(uint256 eventId)
external
view
returns (uint256 classId, bool drawn, uint256 remainingCoverage, uint256 remainingPrincipal)
{
Entry storage entry = _storage().entries[eventId];
uint8 metadata = _storage().eventMetadata[eventId];
classId = metadata & CLASS_MASK;
drawn = metadata & DRAWN_FLAG != 0;
remainingCoverage = entry.remainingCoverage;
remainingPrincipal = entry.remainingPrincipal;
}
/// @notice Total remaining principal for one admitted class, without enumerating event rows.
/// @param classId Class in the configured range `1..Config.NUM_CLASSES`.
/// @return The sum of remaining principal in all live rows of this class.
function remainingPrincipalForClass(uint256 classId) external view returns (uint256) {
if (classId == 0 || classId > Config.NUM_CLASSES) revert CommitmentLedger_InvalidClass(classId);
return _storage().remainingPrincipalByClass[classId];
}
/// @dev Every principal-changing path uses this writer, including registration and release.
function _setPrincipal(CommitmentLedgerStorage storage $, uint256 eventId, uint256 next) private {
Entry storage entry = $.entries[eventId];
uint256 previous = entry.remainingPrincipal;
uint256 classId = $.eventMetadata[eventId] & CLASS_MASK;
$.remainingPrincipalByClass[classId] = $.remainingPrincipalByClass[classId] - previous + next;
entry.remainingPrincipal = next;
}
function _min(uint256 left, uint256 right) private pure returns (uint256) {
return left < right ? left : right;
}
function _storage() private pure returns (CommitmentLedgerStorage storage $) {
assembly {
$.slot := COMMITMENT_LEDGER_STORAGE_LOCATION
}
}
}
src/interfaces/ICascadeBackstop.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/// @title ICascadeBackstop — layer 2 of the loss cascade (ADR-0014)
/// @notice The sGROVE backstop's loss-absorption surface. Losses flow: curator
/// first-loss → THIS backstop → sUSDfr (depositor) principal, in that order,
/// never skipping or inverting a layer (CLAUDE.md §1.3).
/// @dev CONTRACT WITH THE CALLER (DefaultManager): `coverShortfall` MUST transfer
/// exactly `covered` USDfr to `msg.sender` before returning, and `covered <=
/// amount`. The caller burns that USDfr in the same transaction so the supply
/// reduction matches the principal write-down (ADR-0012). The real implementation
/// arrives with Phase H (sGROVE); Phase E tests wire a mock honoring this exact
/// contract, mirroring the MockAttestationOracle pattern from Phase D.
interface ICascadeBackstop is IERC165 {
/// @notice Emitted for every coverage draw, including zero-coverage responses.
event ShortfallCovered(address indexed caller, uint256 requested, uint256 covered);
/// @notice Covers up to `amount` of a realized shortfall from backstop capital.
/// @param eventId Identifies the loss event for durable observability. ADR-0035 deliberately
/// gives this key no separate ceiling or reserved allowance.
/// @param amount The shortfall remaining after curator first-loss absorption.
/// @return covered USDfr actually provided (transferred to `msg.sender`); the
/// implementation bounds this only by the live coverage reserve, so it may be less
/// than `amount`. Under ADR-0035 one event may exhaust layer two entirely; subsequent
/// loss reaches senior principal until real USDfr replenishes the reserve.
function coverShortfall(uint256 eventId, uint256 amount) external returns (uint256 covered);
/// @notice The whole live USDfr reserve available to the next reported shortfall.
/// @dev ADR-0035 removes the former per-event ceiling. This value is therefore identical to
/// `coverageReserve()` and can fall to zero after one event.
function coverageCapacity() external view returns (uint256);
/// @notice Compatibility view for counterfactual accounting; uncapped capacity equals reserve.
/// @param reserve The hypothetical live reserve.
function coverageCapacityAt(uint256 reserve) external view returns (uint256);
/// @notice Compatibility parameters for consumers that still express capacity as a formula.
/// @dev ADR-0035 fixes these to `(BPS, type(uint256).max)`, the identity function. They are not
/// governance parameters and do not create a per-event ceiling.
function coverageCapParameters() external view returns (uint16 proportionalBps, uint256 absoluteCap);
/// @notice The full USDfr reserve currently held for coverage.
function coverageReserve() external view returns (uint256);
/// @notice The shared live reserve an event would reach if processed next.
/// @dev Every event id returns the same value: ADR-0035 creates no event-owned commitment.
/// @param eventId Retained for ABI compatibility and observability; it does not affect capacity.
/// @return remaining The current shared coverage reserve.
function remainingCoverage(uint256 eventId) external view returns (uint256 remaining);
}
src/interfaces/ICommitmentLedger.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title ICommitmentLedger — recorded default rows and shared backstop deliverability.
/// @notice Keeps live row metadata and per-class principal aggregates. Conservative residuals
/// use the five class curator pools followed by the shared sGROVE reserve in constant time.
interface ICommitmentLedger {
function coverDelegate(address backstop, address asset, uint256 eventId, uint256 residual)
external
returns (uint256 covered);
event CommitmentSynced(
uint256 indexed eventId,
uint256 remainingCoverage,
uint256 remainingPrincipal,
uint256 deliverable,
uint256 aggregateDeliverable
);
event CommitmentRegistered(uint256 indexed eventId, uint256 indexed classId, uint256 remainingPrincipal);
event CommitmentPrincipalUpdated(uint256 indexed eventId, uint256 remainingPrincipal);
event CommitmentReleased(uint256 indexed eventId, uint256 releasedDeliverable, uint256 aggregateDeliverable);
/// @notice Register a declared default and increase its class aggregate by the recorded face.
/// @dev Rows retain their declaration order for servicing and independent reference checks.
function register(uint256 eventId, uint256 classId, uint256 remainingPrincipal) external;
/// @notice Re-anchors a live event's residual principal after a recovery or realization.
function updatePrincipal(uint256 eventId, uint256 remainingPrincipal) external;
function sync(uint256 eventId, uint256 remainingCoverage, uint256 remainingPrincipal, uint256 covered)
external
returns (bool firstDraw);
function release(uint256 eventId) external;
function deliverableAggregate() external view returns (uint256);
/// @notice Compute the conservative residual from a fixed number of class aggregates.
/// @return residual Declared and past-due risk remaining after available junior capital.
/// @return pastDueSenior The past-due portion after its policy-prioritized junior allocation.
function conservativeResiduals() external view returns (uint256 residual, uint256 pastDueSenior);
function remainingAggregate() external view returns (uint256);
function consumed(uint256 eventId) external view returns (uint256);
function consumedAggregate() external view returns (uint256);
function deliverable(uint256 eventId) external view returns (uint256);
function state(uint256 eventId)
external
view
returns (uint256 remainingCoverage, uint256 remainingPrincipal, uint256 eventDeliverable);
function eventCount() external view returns (uint256);
function eventAt(uint256 index) external view returns (uint256 eventId);
/// @notice Complete mark-time inputs for one registered event.
/// @dev `remainingCoverage` is an ADR-0035 compatibility field equal to the event's remaining
/// principal once drawn; physical deliverability is bounded separately by the shared
/// reserve during reconstruction.
function eventInfo(uint256 eventId)
external
view
returns (uint256 classId, bool drawn, uint256 remainingCoverage, uint256 remainingPrincipal);
}
src/interfaces/IConservativeImpairmentBook.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title IConservativeImpairmentBook — the raw impairment inputs `ConservativeImpairmentMath` reads
/// @notice Every value the ADR-0022 conservative-redemption NAV needs from the credit book, and
/// nothing else. `DefaultManager` satisfies this with getters that already existed for
/// observability; only `pastDuePrincipal` was added when the arithmetic was extracted.
/// @dev Deliberately NOT `IDefaultManager`: the calculator must not be able to reach a state
/// transition on the book, and a reader interface this narrow makes that structural rather
/// than a review promise. Every member is `view`.
///
/// DO NOT WIDEN THIS INTERFACE to include a non-view function. The calculator is handed an
/// arbitrary `book` address by its caller; keeping the surface read-only is what guarantees a
/// mis-wired or hostile caller cannot use the calculator as a proxy for a privileged call.
interface IConservativeImpairmentBook {
/// @notice Per-class outstanding principal of loans in default whose loss is not yet realized.
function declaredDefaultedPrincipal(uint256 classId) external view returns (uint256);
/// @notice Per-class at-risk principal of facilities flagged past due (AUDIT FIX H-5).
function pastDuePrincipal(uint256 classId) external view returns (uint256);
/// @notice Historical per-class drawn-cohort principal retained for observability.
/// @dev ADR-0035 gives this cohort no distinct coverage formula.
function drawnDefaultPrincipal(uint256 classId) external view returns (uint256);
/// @notice sGROVE coverage already drawn by defaults that are still declared-but-unrealized.
function liveDefaultCoverageConsumed() external view returns (uint256);
/// @notice Aggregate remaining-principal claim of live drawn defaults.
/// @dev ADR-0035 makes this demand-side observability, not physical capacity. The ledger applies
/// the one shared live reserve separately when reconstructing the cascade.
function liveDefaultCoverageRemaining() external view returns (uint256);
/// @notice The sGROVE cascade backstop, or the zero address when none is wired.
function backstop() external view returns (address);
/// @notice When the UNATTESTED past-due cohort last went empty -> non-empty (OWNER DECISION
/// 2026-08-07, G2W). ZERO MEANS UNSET and must fail SAFE to full weight.
/// @dev Added by the G2W merge. `DefaultManager` holds the slot, but the ramp that consumes it
/// lives in `ConservativeImpairmentMath`, so it has to cross the seam. Still `view`.
function pastDueReliefAnchor() external view returns (uint256);
/// @notice Wired module addresses; the calculator uses only `curator`.
function modules()
external
view
returns (
address bridge,
address registry,
address reserves,
address controller,
address curator,
address oracle,
address vault,
address commitmentLedger
);
}
src/interfaces/ICuratorModule.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title ICuratorModule — per-class curator first-loss vaults (ADR-0004)
/// @notice Curators (anchor: Forest Road, $10M/class default; additional curators
/// pluggable per class) post USDfr first-loss capital that absorbs realized
/// losses BEFORE the sGROVE backstop and depositor principal (CLAUDE.md §1.3
/// cascade ordering). Multi-curator stakes in one class share losses exactly
/// pro-rata via internal shares. Withdrawals are constrained by subordination
/// headroom: posted capital protecting live exposure cannot leave.
interface ICuratorModule {
// ── Events ───────────────────────────────────────────────────────────
event CuratorApproved(uint256 indexed classId, address indexed curator, bool approved);
event FirstLossTargetSet(uint256 indexed classId, uint256 target);
// `round` disambiguates share attribution across a wipe-out (audit fix, §3.1).
event FirstLossPosted(
uint256 indexed classId, address indexed curator, uint256 amount, uint256 shares, uint256 round
);
event FirstLossWithdrawn(
uint256 indexed classId, address indexed curator, uint256 amount, uint256 shares, uint256 round
);
/// @notice Emitted on every cascade layer-1 absorption (residual > 0 escalates).
event LossAbsorbed(uint256 indexed classId, uint256 loss, uint256 absorbed, uint256 residual);
/// @notice An optional points notification failed or had no safely available gas.
/// @dev No arbitrary returndata is copied. A dropped points notification never changes
/// first-loss accounting; permissionless points reconciliation remains available.
/// @param module The configured points observer.
/// @param hook The attempted points-hook selector.
/// @param classId The collateral class whose points were being notified.
/// @param curator The affected curator, or zero for a class-wide loss notification.
/// @param gasLimit Maximum requested callback gas; zero means no callback was attempted.
event CuratorPointsHookFailed(
address indexed module, bytes4 indexed hook, uint256 indexed classId, address curator, uint256 gasLimit
);
/// @notice Emitted when a fully-wiped class pool restarts a new share round.
event PoolRoundAdvanced(uint256 indexed classId, uint256 newRound);
/// @notice Share units were divided by a power of two to retain representability.
event PoolSharesNormalized(uint256 indexed classId, uint256 shift, uint256 totalShares);
/// @notice AUDIT FIX (SWEEP-4 S4-R1). A round was CLOSED as economically wiped while a
/// residual balance still stood, so the residual's ownership was snapshotted for the
/// closing cohort instead of being forfeited to the pool.
/// @param classId The class whose round closed.
/// @param closedRound The round that closed.
/// @param residual The USDfr still standing in the pool at the close.
/// @param closedShares Shares of the closed round that share `residual` pro-rata.
/// @param carriedShares Shares of the SUCCEEDING round the closed cohort collectively owns
/// (equal to `residual`, because the new round opens at a share price of exactly 1).
event ClosedRoundSnapshotted(
uint256 indexed classId,
uint256 indexed closedRound,
uint256 residual,
uint256 closedShares,
uint256 carriedShares
);
/// @notice AUDIT FIX (SWEEP-4 S4-R1). A curator's stale-round stake was walked forward through
/// one or more CLOSED rounds. `settledShares == 0` means the stale stake was genuinely
/// worth nothing and was cleared; `toRound` below the class's live round means the walk
/// hit `MAX_CLOSED_ROUND_HOPS` and `claimClosedRound` must be called again.
/// @param classId The class whose stake was settled.
/// @param curator The stake's owner (the settler may be anyone).
/// @param fromRound The round the stake held before the walk.
/// @param toRound The round the stake holds after it.
/// @param staleShares Shares held at `fromRound`.
/// @param settledShares Shares held at `toRound`.
event ClosedRoundSettled(
uint256 indexed classId,
address indexed curator,
uint256 indexed fromRound,
uint256 toRound,
uint256 staleShares,
uint256 settledShares
);
/// @notice Emitted when a default entering a class freezes curator withdrawals.
/// `count` is the number of unresolved defaults now outstanding on the class.
event ClassDefaultFrozen(uint256 indexed classId, uint256 count);
/// @notice Emitted when governance lifts one default freeze from a class.
event ClassDefaultFreezeLifted(uint256 indexed classId, uint256 count);
/// @notice AUDIT FIX (R6-CF1). The ReserveManager whose custody-loss window gates withdrawals.
event ReserveManagerUpdated(address indexed reserves);
/// @notice AUDIT FIX (R6-CF1). The governor the pre-arm duration is derived from (0 = the
/// `Config` launch parameters are used as the floor and nothing overrides them).
event GovernorUpdated(address indexed governor);
/// @notice AUDIT FIX (R6-CF1). A guardian armed the custody freeze ahead of governance.
/// @param guardian The arming guardian.
/// @param expiry Unix time at which the pre-arm lapses on its own.
/// @param count Consecutive pre-arms used out of the budget, after this one.
event CustodyFreezePreArmed(address indexed guardian, uint64 expiry, uint32 count);
/// @notice AUDIT FIX (R6-CF1). Governance declared a FALSE ALARM: the guardian pre-arm limb is
/// cleared and the budget replenished. This can NEVER release a genuine custody freeze
/// — the derived limbs in `IReserveManager.custodyLossUnabsorbed` stand on their own.
event CustodyFreezePreArmCancelled(uint64 previousExpiry);
/// @notice AUDIT FIX (F3-PA-a). Governance replenished the guardian's pre-arm budget while
/// LEAVING the standing pre-arm in force — "we looked, the incident is real, keep
/// going". `expiry` is echoed unchanged precisely so an observer can verify that the
/// protection survived the replenishment.
/// @param spent Budget units returned to the guardian.
/// @param expiry The standing pre-arm expiry, unchanged by this call.
event CustodyFreezePreArmBudgetReplenished(uint32 spent, uint64 expiry);
/// @notice AUDIT FIX (F3-PA-b). A previous pre-arm had lapsed and layer-1 capital had stood
/// unfrozen for the full `custodyPreArmCooldown()`, so the consecutive counter reset
/// and this arm opened a NEW episode.
/// @param spent Budget the lapsed episode had used.
/// @param lapsedExpiry Expiry of the episode that just ended.
event CustodyFreezePreArmEpisodeReset(uint32 spent, uint64 lapsedExpiry);
/// @notice AUDIT FIX (F3-PA-c). THE CAP BOUND. One pre-arm window no longer outlasts the live
/// governance path, so the freeze WILL lapse before governance can ratify it unless
/// `replenishCustodyPreArmBudget` carries it. Emitted at the arm so the condition can
/// never arise silently; `script/Validate.s.sol` refuses a deployment in this regime.
/// @param livePath The unbounded `votingDelay + votingPeriod + minDelay` reading, in seconds.
/// @param duration The window actually granted, bounded by `CUSTODY_PRE_ARM_MAX_PATH`.
/// @param count Consecutive pre-arms used out of the budget, after this one.
event CustodyFreezePreArmTruncated(uint256 livePath, uint64 duration, uint32 count);
// ── Errors ───────────────────────────────────────────────────────────
error Curator_ZeroAddress();
error Curator_ZeroAmount();
/// @notice The proposed points module has no code and is refused as a wiring error.
/// @dev P-48b originally prevented an uncatchable high-level-call code-size revert.
/// Bounded observers also tolerate legacy post-install code disappearance, while
/// new codeless configurations remain invalid.
/// @param module The codeless address that was refused.
error Curator_PointsModuleNotAContract(address module);
error Curator_UnknownClass(uint256 classId);
error Curator_NotApprovedCurator(uint256 classId, address curator);
error Curator_InsufficientStake(uint256 classId, address curator, uint256 requested, uint256 posted);
error Curator_HeadroomExceeded(uint256 classId, uint256 requested, uint256 headroom);
/// @notice Withdrawals are frozen because the class has an unresolved default
/// (audit R4-EC2: stops a curator front-running realizeLoss to duck a loss).
error Curator_ClassDefaultFrozen(uint256 classId);
/// @notice liftDefaultFreeze called on a class with no outstanding default freeze.
error Curator_NotFrozen(uint256 classId);
/// @notice AUDIT FIX (R6-CF1). Withdrawals are frozen because a reserve-CUSTODY loss is
/// recognised, observable or incompletely absorbed, or because a guardian has
/// pre-armed the freeze. Curator capital is cascade LAYER 1 for that loss and may not
/// exit ahead of it — the custody twin of `Curator_ClassDefaultFrozen` (R4-EC2).
error Curator_CustodyLossFrozen();
/// @notice AUDIT FIX (R6-CF1). No ReserveManager is wired, so the custody-loss window cannot
/// be evaluated. Withdrawals fail CLOSED rather than proceeding blind.
error Curator_ReserveNotWired();
/// @notice AUDIT FIX (R6-CF1). The guardian's consecutive pre-arm budget is spent. Only
/// governance can replenish it, which is what bounds a unilateral guardian freeze.
error Curator_PreArmBudgetExhausted(uint32 requested, uint32 max);
/// @notice AUDIT FIX (R6-CF1). `cancelCustodyPreArm` with nothing armed and no budget used.
error Curator_NoPreArm();
/// @notice AUDIT FIX (R6-CF1). `setReserveManager` was given an address that is not a
/// ReserveManager. Wiring the freeze to the wrong contract would make the guard read
/// someone else's state, so this fails loudly rather than accepting it.
error Curator_InvalidReserveManager(address reserves);
/// @notice AUDIT FIX (R6-CF1). `setGovernor` was given an address with no code, which could
/// never supply a live governance path.
error Curator_InvalidGovernor(address governor);
error Curator_ReserveManagerChangeFrozen();
error Curator_ReserveLossWithdrawalsFrozen();
error Curator_ShareCapacityExceeded(uint256 amount, uint256 availableShares);
/// @notice AUDIT FIX (SWEEP-4 S4-R1). The caller holds a stake in a round that closed more than
/// one round ago, so a single conversion cannot bring it to the live round. Call
/// `claimClosedRound` (permissionless) until `stakeRound == liveRound`, then retry.
/// Posting or withdrawing is REFUSED rather than silently erasing the residual claim.
error Curator_UnsettledClosedRound(uint256 classId, uint256 stakeRound, uint256 liveRound);
// ── Curator paths ────────────────────────────────────────────────────
/// @notice Posts `amount` USDfr of first-loss capital to `classId`'s pool.
/// Caller must be an approved curator for the class.
function postFirstLoss(uint256 classId, uint256 amount) external;
/// @notice Withdraws `amount` USDfr of the caller's stake, capped by BOTH the
/// caller's pro-rata stake and the class's subordination headroom.
function withdrawFirstLoss(uint256 classId, uint256 amount) external;
/// @notice AUDIT FIX (SWEEP-4 S4-R1). Converts `curator`'s stake in a CLOSED round into its
/// pro-rata slice of the succeeding round's shares. PERMISSIONLESS — anyone may settle
/// anyone, because a curator who cannot settle cannot post or withdraw either, and
/// layer-1 liveness must not depend on one address being available.
/// @dev Moves NO value: the shares it assigns were minted at the close and have been part of
/// `poolShares(classId)` ever since. It is a pure re-attribution of ownership, which is why
/// it is not pausable and not gated by either withdrawal freeze — neither of those governs
/// attribution, and both still bind on `withdrawFirstLoss`.
/// Idempotent: a stake already on the live round is a no-op. Call it repeatedly to walk a
/// stake through several consecutive closes.
function claimClosedRound(uint256 classId, address curator) external;
// ── Cascade (credit layer only) ──────────────────────────────────────
/// @notice Absorbs up to `loss` from the class pool (cascade layer 1). Transfers
/// the absorbed USDfr to `msg.sender` (the DefaultManager), which burns it
/// in the same transaction against the principal write-down (ADR-0012).
/// @return absorbed Amount taken from the pool (== min(loss, pool balance)).
/// @return residual Loss remaining for the next cascade layer.
function absorbLoss(uint256 classId, uint256 loss) external returns (uint256 absorbed, uint256 residual);
/// @notice Absorbs a classless protocol loss across all five pools, weighted by balances
/// snapshotted before any pool is changed. Rounding dust is assigned deterministically
/// to the lowest-numbered non-empty pools with snapshot headroom.
/// @dev Transfers the aggregate absorbed USDfr to the caller for same-transaction burning.
function absorbGlobalLoss(uint256 loss) external returns (uint256 absorbed, uint256 residual);
// ── Default freeze (audit R4-EC2) ────────────────────────────────────
/// @notice Records that a facility in `classId` has entered default, freezing curator
/// withdrawals for the class until governance lifts it. Called by the
/// DefaultManager (CREDIT_ROLE) on declareDefault / liquidate. Increments an
/// unresolved-default counter so concurrent defaults each require a lift.
function freezeOnDefault(uint256 classId) external;
/// @notice Governance (timelock) lifts one default freeze from `classId` once a
/// workout resolves. Reverts if the class has no outstanding freeze.
function liftDefaultFreeze(uint256 classId) external;
/// @notice Number of unresolved defaults freezing withdrawals on a class (0 = open).
function unresolvedDefaults(uint256 classId) external view returns (uint256);
// ── Custody-loss freeze (audit R6-CF1) ───────────────────────────────
/// @notice AUDIT FIX (R6-CF1). True while curator first-loss capital is frozen by a
/// reserve-CUSTODY loss (recognised, observable, or incompletely absorbed) or by a
/// live guardian pre-arm. Class-independent: a custody loss is allocated across ALL
/// five pools by `absorbGlobalLoss`, so the freeze is protocol-wide.
/// @dev Reads as TRUE when no ReserveManager is wired. "Cannot tell" must never read as
/// "clear" on a guard whose whole job is to stop capital leaving ahead of a loss.
function custodyFreezeActive() external view returns (bool);
/// @notice AUDIT FIX (R6-CF1). Guardian arms the custody freeze ahead of governance, for
/// losses that are known but not yet visible on-chain (a custodian insolvency, a legal
/// seizure, an off-chain balance frozen). A guardian may ARM but has NO release.
function preArmCustodyFreeze() external;
/// @notice AUDIT FIX (R6-CF1). Governance declares a FALSE ALARM: clears the guardian pre-arm
/// limb and replenishes the pre-arm budget.
/// @dev It CANNOT release a real custody freeze: the derived limbs are unaffected. That is why
/// giving governance this cancel does not hand it a loss-dodging lever.
///
/// AUDIT FIX (F3-PA-a). This is the FALSE-ALARM lever only. To keep a REAL incident frozen
/// while returning budget to the guardian, use `replenishCustodyPreArmBudget` — using this
/// one for that purpose destroys the protection it was called to extend.
function cancelCustodyPreArm() external;
/// @notice AUDIT FIX (F3-PA-a). Governance returns the guardian's pre-arm budget WITHOUT
/// touching the standing pre-arm — "we looked, the incident is real, keep going".
/// @dev THE HIGH THIS CLOSES: `cancelCustodyPreArm` was the only replenishment path and it
/// zeroes `custodyPreArmExpiry`, so regaining budget destroyed the active protection and
/// opened a window in which curator first-loss could leave ahead of a loss it is cascade
/// LAYER 1 for. Reverts with `Curator_NoPreArm` when no budget has been spent.
function replenishCustodyPreArmBudget() external;
/// @notice AUDIT FIX (R6-CF1). Current guardian pre-arm: lapse time and CONSECUTIVE budget used
/// within the current episode (see `custodyPreArmCooldown`).
function custodyPreArm() external view returns (uint64 expiry, uint32 count);
/// @notice AUDIT FIX (R6-CF1). How long one guardian pre-arm lasts. DERIVED from the live
/// governance path (`votingDelay + votingPeriod + timelock minDelay`) with the `Config`
/// launch parameters as a floor, so it can never expire before governance could
/// possibly have ratified it.
/// @dev Strictly greater than `custodyPreArmGovernancePath()` at every parameterisation.
function custodyPreArmDuration() external view returns (uint64);
/// @notice AUDIT FIX (F3-PA-c). The governance path the duration was derived from: the longer
/// of the `Config` launch floor and the live reading, bounded by
/// `CUSTODY_PRE_ARM_MAX_PATH`.
function custodyPreArmGovernancePath() external view returns (uint64);
/// @notice AUDIT FIX (F3-PA-c). False when the path bound BINDS — i.e. one pre-arm window no
/// longer outlasts the LIVE governance path and `replenishCustodyPreArmBudget` must
/// carry the difference. `script/Validate.s.sol` refuses a deployment where this is
/// false, and `preArmCustodyFreeze` emits `CustodyFreezePreArmTruncated` when it arms
/// into that regime.
function custodyPreArmCoversLiveGovernancePath() external view returns (bool);
/// @notice AUDIT FIX (F3-PA-b). How long layer-1 capital must stand UNFROZEN after a pre-arm
/// lapses before the guardian's consecutive budget resets and a new episode may open.
function custodyPreArmCooldown() external view returns (uint64);
/// @notice AUDIT FIX (R6-CF1). Wires the ReserveManager whose custody-loss window gates
/// withdrawals. Timelocked governance only; zero explicitly unwires (and freezes).
function setReserveManager(address reserves) external;
/// @notice AUDIT FIX (R6-CF1). Wires the governor the pre-arm duration is derived from. Zero
/// leaves the `Config` launch parameters standing as the sole source.
function setGovernor(address governor) external;
function governanceUnpause() external;
// ── Views ────────────────────────────────────────────────────────────
/// @notice Current pool balance for a class (18-dec USDfr).
function poolBalance(uint256 classId) external view returns (uint256);
/// @notice A curator's current pro-rata stake value in a class.
/// @dev AUDIT FIX (SWEEP-4 S4-R1, FOUR-INPUT COMPOSITION). Live-round values are exact. A
/// closed-round value is a conservative pre-settlement quote because the executable
/// remaining/remaining allocation depends on settlement order. Partial holders round
/// down; only the unique holder of a snapshot's whole remaining cohort may receive its
/// one-unit remainder. It may read zero for sub-wei carry or beyond the bounded walk
/// without erasing the claim; call `claimClosedRound` to materialize the exact live stake.
function postedOf(uint256 classId, address curator) external view returns (uint256);
/// @notice AUDIT FIX (SWEEP-4 S4-R1). The residual-claim snapshot for a CLOSED round.
/// @param classId The class.
/// @param round The closed round.
/// @return closedShares Shares of `round` that have not yet been settled.
/// @return carriedShares Shares of round `round + 1` those unsettled shares collectively own.
function closedRound(uint256 classId, uint256 round)
external
view
returns (uint256 closedShares, uint256 carriedShares);
/// @notice Required subordination for a class: min(first-loss target, live class
/// exposure). Capital up to this level cannot be withdrawn.
function requiredFirstLoss(uint256 classId) external view returns (uint256);
/// @notice Withdrawable excess above the subordination requirement.
function headroom(uint256 classId) external view returns (uint256);
/// @notice Governance-set first-loss target for a class (ADR-0004: $10M default).
function firstLossTarget(uint256 classId) external view returns (uint256);
/// @notice True if `curator` may post first-loss to `classId`.
function isApprovedCurator(uint256 classId, address curator) external view returns (bool);
function reserveManager() external view returns (address);
function modules() external view returns (address usdfr, address registry, address feeVault);
}
src/libraries/Config.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title Config
/// @notice Single source of truth for token naming and protocol default parameters
/// (brief Part 12: names are final but kept in one module so a rebrand is a
/// single change).
library Config {
// ── Token naming (final per brief Part 12) ──────────────────────────
string internal constant USDFR_NAME = "Forest Road Dollar";
string internal constant USDFR_SYMBOL = "USDfr";
string internal constant SUSDFR_NAME = "Staked Forest Road Dollar";
string internal constant SUSDFR_SYMBOL = "sUSDfr";
string internal constant GROVE_NAME = "Forest Road Grove";
string internal constant GROVE_SYMBOL = "GROVE";
string internal constant SGROVE_NAME = "Staked Forest Road Grove";
string internal constant SGROVE_SYMBOL = "sGROVE";
// ── Collateral class IDs (ADR-0003 as amended: all FIVE live at genesis) ──
uint256 internal constant CLASS_FILM_TAX_CREDITS = 1;
uint256 internal constant CLASS_RENEWABLE_ENERGY = 2;
uint256 internal constant CLASS_LIFE_SCIENCES = 3;
uint256 internal constant CLASS_REAL_ESTATE = 4;
/// @dev Marked-to-market, related-party class (ADR-0015) — distinct margin/
/// liquidation model, NOT the receivable model of classes 1-4.
uint256 internal constant CLASS_DIGITAL_ASSETS = 5;
uint256 internal constant NUM_CLASSES = 5;
// ── Credit-layer defaults (ADR-0004 / ADR-0014; governance-adjustable) ──
/// @dev USD amounts in 18 decimals (USDfr units).
uint256 internal constant DEFAULT_FIRST_LOSS_PER_CLASS = 10_000_000e18;
uint256 internal constant SGROVE_UNBONDING_PERIOD = 21 days;
// Reward streaming window (ADR-0021 / audit R4-EC1): notified rewards drip linearly
// over this period rather than distributing instantly, so rewards accrue in real time
// (Pendle-compatible) and cannot be sandwiched by a deposit-before-harvest. Governance
// tunable via setRewardsDuration, bounded by SGROVE_MAX_REWARDS_DURATION.
uint64 internal constant SGROVE_REWARDS_DURATION = 7 days;
uint64 internal constant SGROVE_MAX_REWARDS_DURATION = 365 days;
// ── Governance defaults (ADR-0013/0021; FR-controlled at launch) ─────
/// @dev Fixed at genesis, minted to the Forest Road treasury (ADR-0013).
uint256 internal constant GROVE_INITIAL_SUPPLY = 1_000_000_000e18;
uint48 internal constant GOV_VOTING_DELAY = 1 days;
/// @dev Fresh Ethereum genesis: owner-approved 2026-09-18; existing proxy settings persist.
uint32 internal constant GOV_VOTING_PERIOD = 2 days;
uint256 internal constant GOV_PROPOSAL_THRESHOLD = 1_000_000e18; // 0.1% of supply
uint256 internal constant GOV_QUORUM_FRACTION = 4; // % of total votes
uint256 internal constant TIMELOCK_MIN_DELAY = 2 days;
/// @dev C-01 reserve-loss pre-arm floor. The live arm duration is derived from the
/// bound Governor and Timelock at arm time and may be longer; this immutable
/// floor prevents a broken or shortened timing dependency from failing open.
uint256 internal constant RESERVE_LOSS_MIN_PREARM_DURATION = 11 days;
uint256 internal constant RESERVE_LOSS_SCHEDULING_SLACK = 1 days;
/// @dev Preserve the original curator pre-arm floor when launch voting is shortened.
/// Longer live governance schedules still extend the derived protection.
uint256 internal constant CURATOR_PRE_ARM_MIN_GOVERNANCE_PATH = 10 days;
/// @dev Protocol fee on distributed interest (waterfall), in bps. Launch default
/// is deliberately modest; governance-adjustable; economic-review item.
uint256 internal constant DEFAULT_PROTOCOL_FEE_BPS = 1_000; // 10% of interest
/// @dev AUDIT FIX (SWEEP-2 S2-F1) — PERMANENT HARD CAP ON THE INTEREST PROTOCOL FEE.
/// DO NOT DELETE AND DO NOT RAISE WITHOUT FOREST ROAD DIRECTION.
///
/// Before this, `WaterfallEngine.setProtocolFee` was bounded only by `Config.BPS` — it was
/// the ONLY fee rate in the protocol with no permanent ceiling, while its three siblings
/// (`setOriginationFee` -> `MAX_ORIGINATION_FEE_BPS`, `sUSDfr.setPerformanceFee` ->
/// `MAX_PERFORMANCE_FEE_BPS`, `setManagementFee` -> `MAX_MANAGEMENT_FEE_BPS`) all carry
/// one and two of those are PUBLISHED to holders (`maxPerformanceFeeBps()`,
/// `maxManagementFeeBps()`) and described here as "permanent in v1". MEASURED: 10,000 bps
/// was accepted and took the ENTIRE senior yield leg (`toVault` 0, `toFee` the whole
/// interest receipt). Because `_routeInterest` takes this fee FIRST, off the same senior
/// income stream the vault's 20% performance cap protects, total capture of senior yield
/// was reachable AROUND a cap the protocol advertises as permanent — and the fee recipient
/// holds plain USDfr, so it is not a cascade layer.
///
/// The LEVEL mirrors `MAX_PERFORMANCE_FEE_BPS` (20%), i.e. 2x the launch default, which
/// is the house convention for "a permanent ceiling with real governance room under it".
/// The level is an economic-review item; the EXISTENCE of the ceiling is not.
uint16 internal constant MAX_PROTOCOL_FEE_BPS = 2_000; // 20% of interest — permanent in v1
/// @dev Protocol-level performance fee on sUSDfr NAV gains above the global,
/// post-fee high-water mark. Launches at 10% and may only be changed
/// prospectively by timelocked governance. The hard cap is permanent in v1.
uint16 internal constant DEFAULT_PERFORMANCE_FEE_BPS = 1_000; // 10% of profit
uint16 internal constant MAX_PERFORMANCE_FEE_BPS = 2_000; // 20% of profit
/// @dev Effective-annual sUSDfr management fee on a 365-day basis. Launches disabled
/// and may only be enabled prospectively by timelocked governance. Fractional
/// periods use geometric retention; the hard cap is permanent in v1.
uint16 internal constant DEFAULT_MANAGEMENT_FEE_BPS = 0;
uint16 internal constant MAX_MANAGEMENT_FEE_BPS = 200; // 2% per 365-day year
uint64 internal constant MANAGEMENT_FEE_YEAR = 365 days;
/// @dev Origination fee charged at facility funding, in bps of principal (OID
/// mechanics: the borrower nets principal minus fee). Market range for the
/// book's verticals is ~1-2% (ADR-0019); per-class governance-adjustable,
/// capped at MAX_ORIGINATION_FEE_BPS; economic-review item.
uint16 internal constant DEFAULT_ORIGINATION_FEE_BPS = 200; // 2% of principal (Forest Road direction)
uint16 internal constant MAX_ORIGINATION_FEE_BPS = 1_000; // 10% hard cap
/// @dev Margin-call cure window for marked-to-market classes (ADR-0015:
/// "hours-to-days"). Governance-adjustable per class; economic-review item.
uint64 internal constant DEFAULT_MARGIN_CURE_WINDOW = 1 days;
// ── Liquidity-layer defaults (ADR-0010/0022; governance-adjustable) ──
/// @dev Settlement HEARTBEAT (ADR-0022): how often `closeEpoch` may run and refresh
/// the liquidity budget. Under the ADR-0022 cooldown model this is NOT the
/// holding period — `DEFAULT_REDEEM_COOLDOWN` is. The heartbeat must be SHORT
/// relative to the cooldown so the effective wait ≈ cooldown (no compounding).
/// Heartbeat/liquidity calibration is an economic-review item (ADR-0022 §X.5).
uint64 internal constant DEFAULT_EPOCH_DURATION = 1 days;
/// @dev Share of the treasury's idle canonical-USDC liquidity a settlement may
/// distribute to the queue PER
/// HEARTBEAT, leaving the remainder for direct USDfr redemptions. Rescaled from
/// the legacy 50%/30-day batch to preserve ~50%/30-day throughput at a 1-day
/// heartbeat (5000/30 ≈ 167). Economic-review item (ADR-0022 §X.5).
uint16 internal constant DEFAULT_EPOCH_LIQUIDITY_BPS = 167; // ~1.67%/day ≈ 50%/30d
/// @dev ADR-0022: forced per-request redemption cooldown. A queued redemption cannot
/// settle until `requestedAt + DEFAULT_REDEEM_COOLDOWN`. Matches
/// `SGROVE_UNBONDING_PERIOD` (21 days) — long enough that a senior cannot exit
/// ahead of a foreseeable loss (front-running / loss-dodge defense).
uint64 internal constant DEFAULT_REDEEM_COOLDOWN = 21 days;
/// @dev AUDIT FIX (SWEEP-2 CSG-F2) — the UPPER bound on `RedemptionQueue.setRedeemCooldown`.
/// The LOWER bound is `DEFAULT_REDEEM_COOLDOWN` itself and is not a separate constant on
/// purpose: the G2W relief ramp in `CollateralRegistry.conservativeSeniorMark` is written
/// against that exact constant, so the floor must BE it — a second constant is a second
/// thing to forget to move (SEAM-1). 180 days is the same order as
/// `SGrove.setUnbondingPeriod`'s `AUDIT FIX (L)` ceiling and exists for the same reason:
/// an unbounded setter can permanently freeze every queued senior exit by fat finger.
uint64 internal constant MAX_REDEEM_COOLDOWN = 180 days;
/// @dev C-1 anti-dust-wedge floor. Minimum REALIZED value (in USDfr, 18 decimals) a
/// redemption request must be worth to enter the queue — $1. `closeEpoch` never burns a
/// position worth zero at the conservative mark; it stops there, so a sub-wei "dust" head
/// could otherwise wedge the queue for the real positions behind it. Barring dust at entry
/// makes that wedge reachable only when the exchange rate has collapsed by >1e18x (a
/// >99.9999999999999999% senior loss), at which point every realistically-sized position
/// is ALSO worth under a wei and halting the queue is the correct behaviour, not griefing.
/// Measured at the REALIZED rate (`convertToAssets`), not the conservative one, so a
/// declared-but-unrealized impairment does not lock new exits out of the queue.
/// Governance-tunable via `RedemptionQueue.setMinRedemptionValue`.
uint256 internal constant DEFAULT_MIN_REDEMPTION_VALUE = 1e18; // 1 USDfr ($1)
// ── Optional senior-yield vesting (ADR-0023; governance-adjustable) ──
/// @dev Realized senior yield may be vested linearly into `sUSDfr.totalAssets()`
/// instead of landing as an instant step. Only ALREADY-REALIZED yield can be
/// streamed — nothing forward-looking is ever pre-credited, so ADR-0002
/// variable-yield pass-through is untouched. Pendle accepts a valid stepwise SY
/// exchange rate; smoothing is an optional market-design control against
/// payment-timing games and abrupt asset-denominated price moves, not a Pendle
/// protocol prerequisite. Forest Road selected instant recognition for launch.
/// Governance may enable a non-zero window prospectively after economic review.
uint64 internal constant DEFAULT_YIELD_VESTING_PERIOD = 0;
/// @dev Hard ceiling on a newly opened stream. The vault also stores an absolute stream
/// deadline that non-zero governance re-tunes and rollovers may shorten but never
/// extend, so alternating settings cannot defer the same realized yield indefinitely.
uint64 internal constant MAX_YIELD_VESTING_PERIOD = 30 days;
/// @notice RAMP POSTURE (Forest Road direction, 2026-07-21): concentration limits are
/// seeded WIDE OPEN so idle deposit capital can be deployed into originations —
/// initially a facility to the digital-assets book — without a concentration
/// dimension blocking it before the book has any diversity to measure.
/// @dev At `BPS` (100%) the admission test `exp > limitBps * base / BPS` reduces to
/// `exp > base`, and no single dimension can exceed the book, so NOTHING BINDS.
/// Two consequences the operator must hold in mind, both stated rather than implied:
/// 1. Concentration TELEMETRY GOES DARK. `isOverConcentrated`, the drift events and
/// `concentrationHeadroom` all measure against the configured limit, so at 100%
/// they report "clean" unconditionally. There is no on-chain early warning while
/// this posture holds; monitoring must come from the `ExposureRecorded` stream.
/// 2. RATCHETING DOWN LATER IS A CLIFF. Limits are ADMISSION control and a standing
/// breach is permitted (a decrease can never be blocked, or a risk limit could
/// veto a loss being realized). So whatever is concentrated when a real limit is
/// set will instantly read as breached and be frozen from further growth until
/// the book grows around it. Set the first real limits AT or slightly above the
/// actual composition at that time, then step down — do not jump straight to the
/// target.
/// `Validate.s.sol` prints an unmissable posture block whenever this is in force, so
/// an unlimited deployment can never produce output identical to a limited one.
uint16 internal constant RAMP_CONCENTRATION_LIMIT_BPS = 10_000; // 100% = unbounded
uint256 internal constant BPS = 10_000;
/// @notice Forward weight, in bps, that an UNATTESTED permissionless past-due mark
/// (`DefaultManager.markPastDue`) carries in the conservative redemption NAV,
/// relative to an ATTESTED declared default. Used as the fallback whenever
/// `DefaultManager`'s governed slot reads zero (see `pastDueWeightBps()`).
/// @dev OWNER DECISION (Forest Road, 2026-08-07): "An unattested, permissionless past-due
/// mark should NOT carry the same forward weight as an attested declared default."
///
/// DERIVED, NOT INVENTED. The protocol already governs an evidence ladder — but only on
/// the marked-to-market side, where the three rungs are per-class registry parameters:
/// - `maxLtvBps` the rung the protocol is willing to be exposed at (healthy);
/// - `marginCallLtvBps` the rung at which a PERMISSIONLESS, REVERSIBLE early warning
/// fires (`marginCall`) — forward impairment weight ZERO, it only
/// starts a cure clock;
/// - `liquidationLtvBps` the terminal rung, where `liquidate` records the FULL
/// outstanding into the impairment pool and `realizeLoss` becomes
/// reachable — forward impairment weight ONE.
/// `markPastDue` is the receivable-side analogue of the MARGIN-CALL rung: permissionless,
/// reversible, early, and strictly BEFORE the terminal attested rung (`declareDefault`).
/// Governance placed that early rung exactly half way along the governed deterioration
/// band. From the mainnet-v1 class-5 tuple in `script/Deploy.s.sol`
/// (maxLtv 5_000, marginCall 6_500, liquidation 8_000):
///
/// (marginCallLtvBps - maxLtvBps) / (liquidationLtvBps - maxLtvBps)
/// = (6_500 - 5_000) / (8_000 - 5_000) = 1_500 / 3_000 = 1/2 = 5_000 bps.
///
/// WHY NOT THE ADVANCE RATE ALONE. `maxLtvBps`/`ltvBps` cannot supply this weight, and the
/// reasoning is recorded here so it is not re-attempted: the advance rate is DEFINED as the
/// break-even recovery on the attested claim face (ClaimBridge documents the denominator as
/// `principal * BPS / ltvBps`). Senior loss is `max(0, principal - recovery)`, so at a
/// recovery equal to the advance rate the loss is identically ZERO — the advance rate
/// derives a weight of 0, which re-opens H-5 and D5-03. Worse, every variant that forces a
/// positive number out of it (haircut on face, re-advance against carried principal) is
/// MONOTONE THE WRONG WAY: it marks a more conservatively underwritten facility harder.
///
/// DO NOT set this to zero (re-opens H-5: a conflicted servicer can sit on a declaration
/// while seniors exit at par) or to `BPS` (restores the defect this constant fixes).
/// `CollateralRegistry.setPastDueWeight` enforces both bounds.
uint256 internal constant DEFAULT_PAST_DUE_WEIGHT_BPS = 5_000; // 50%
/// @notice sUSDfr entry guard (audit H-3 residual): the maximum ratio of the STRANDED,
/// realized-but-unvested yield stream (`sUSDfr.unvestedYield()`) to the DEPOSIT BASE
/// (`sUSDfr.totalAssets()`) that vault entry tolerates before `deposit`/`mint` close as
/// degenerate.
/// @dev THE HAZARD (ADR-0023): the vault physically holds realized yield that vests linearly
/// into `totalAssets()` over a window and is EXCLUDED from `totalAssets()` until it does.
/// Deposits price on `totalAssets()` (OZ's un-overridden `_convertToShares`), so a
/// depositor entering while that stranded stream is large relative to the base buys shares
/// cheaply and then skims a pro-rata slice of the stream as it vests — extracting from the
/// incumbents who funded it. The hazard scales with `unvestedYield() / totalAssets()`, so
/// the guard keys on exactly that ratio.
///
/// CALIBRATION (economic-review item; audit finding #3 re-key from 10 to 3, then audit
/// R16-01). `sUSDfr._capStreamToBase` enforces a retention boundary against the ACTUAL
/// staked base on both sides of the vault: after every yield delivery AND before every
/// queue outflow, at most `1/(K+1)` of physical vault USDfr remains unvested and any
/// excess is recognized immediately. A healthy low-staking vault therefore cannot be
/// closed by receiving a payment that is large relative to deposits (FRV-FS-03), nor by
/// an ordinary settlement shrinking the base under a live stream (RC-03).
/// The guard remains meaningful after a senior write-down, which burns the recognized
/// base while leaving an already-live stream physically present.
///
/// WHY 3 AND NOT 10 (the audit residual). The OLD `K = 10` reopened entry the moment the
/// ratio fell to 10 — with the stranded stream still 10/11 (~91%) of the vault balance —
/// leaving a near-total skim band `(0, 10]` open. It did NOT "close the entire band": near
/// the top of that band a fresh depositor could still skim ~91% of the vault as the stream
/// vested. Dropping to `K = 3` collapses the open band to `(0, 3)`. `K = 3` bounds the
/// excluded stream at the closure point to 3/4 (~75%) of physical vault assets. It is a
/// DIMENSIONLESS ratio, not a wei level, so it holds identically at every vault scale.
///
/// CORRECTION (AUDIT R16-01, HIGH — the previous justification of the open band was
/// FALSE; do not restore it). This comment used to argue that the top of the `(0, K]` band
/// is "only reachable while the withheld stream is a MAJORITY of the vault, an
/// already-catastrophic near-total-write-down state, never a healthy one". That was wrong,
/// and `K` was never what bounded a routine deposit's skim. The FRV-FS-03 inflow leg
/// created exactly that ratio in a HEALTHY vault: the cap retained `K/(K+1)` of the
/// balance, the largest retention the guard tolerates, which parks the vault at precisely
/// `unvestedYield() == K * totalAssets()` — and `_isDegenerate`'s strict `>` left entry
/// OPEN on that point. Servicing payments are sized off book principal, not off live
/// sUSDfr supply, so any payment large relative to the staked base reached it. What bounds
/// the routine skim is the CAP's retention target, now `1/(K+1)`: healthy operation parks
/// at ratio `1/K`, a factor of `K^2` inside this guard, with a minority (25%) of the
/// vault's cash excluded, and the boundary itself is now CLOSED (`>=`). The band between
/// `1/K` and `K` is reachable only through a realized loss or a governance re-pricing of
/// the vesting window.
///
/// Kept a constant rather than a governance-tunable for
/// this pass: like `SUSDFR_MAX_SHARE_PRICE_COLLAPSE`, it is a defensive safety floor, not an
/// operating knob, and adding storage/setter surface to the namespaced vault struct for it
/// is unwarranted complexity here; a future pass may promote it to a governed parameter.
/// See `SUSDfr._isDegenerate` and `SUSDfr._capStreamToBase`.
uint256 internal constant SUSDFR_MAX_STRANDED_YIELD_RATIO = 3;
/// @dev AUDIT R15-01. Vault entry closes once the realized per-share rate has collapsed to
/// below `1 / SUSDFR_DEGENERATE_RATE_DIVISOR` of the stored high-water mark.
///
/// WHY A SECOND BAND IS NEEDED. `SUSDFR_MAX_STRANDED_YIELD_RATIO` above keys on
/// `unvestedYield()`, which is identically zero at the launch instant-recognition policy
/// (`DEFAULT_YIELD_VESTING_PERIOD == 0`). That band therefore cannot fire at launch,
/// leaving only the `totalAssets() == 0` POINT — and one wei of a permissionless USDfr
/// transfer steps off a point. `_isDegenerate`'s own rationale states the hazard is the
/// whole neighbourhood, not the point; this restores the neighbourhood at every vesting
/// setting.
///
/// WHY PAR IS THE REFERENCE. The stored high-water mark was tried first and rejected:
/// `_accrueFees`'s empty-supply branch ratchets it to `(assets + 1) * 1e18` whenever any
/// balance exists while `totalSupply() == 0`, so a pre-seed donation could inflate the
/// hurdle arbitrarily and then permanently close entry through this band. That is
/// harmless while the HWM only suppresses fees, and becomes a brick the moment entry
/// depends on it — the invariant suite caught exactly that. Par is derived from the
/// token's own decimals, is scale-free, and no actor can move it.
///
/// WHY 100. The band must separate a catastrophic collapse from a merely bad year, because
/// closing entry is a governance event: a vault below 1% of its high-water mark is the
/// near-total write-down the guard exists for, while a 50%-drawdown vault stays open to
/// new capital. ECONOMIC-REVIEW ITEM, on the same footing as `K = 3` above — the shape is
/// a safety floor, but the exact multiple is a judgement about when recapitalization must
/// route through governance rather than through an ordinary deposit.
uint256 internal constant SUSDFR_DEGENERATE_RATE_DIVISOR = 100;
}
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.