Verified contractExactBUSL-1.1
SettlementLiquidityLib
Address0x2d825fb582308f1f8a04efcdd68f9212656b54b1
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.30
- Same code
1 more 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,450
- Creation transaction
- 0x206bf564b7…3aa7a4e800
3 files
- src/libraries/SettlementLiquidityLib.solmain10.02 KB
- src/interfaces/IReserveManager.sol31.28 KB
- src/libraries/Config.sol23.1 KB
src/libraries/SettlementLiquidityLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
import {IReserveManager} from "../interfaces/IReserveManager.sol";
import {Config} from "./Config.sol";
/// @notice Qualified treasury cash excludes primary mint inflows until the existing exit cooldown.
/// @dev Exact timestamps, logarithmic lookup and logarithmic tail cancellation avoid deposit-count
/// denial of service. Cash outflows cancel newest unseasoned cash first, preserving older cash's
/// age across a primary mint/redeem round trip. Every quote remains bounded by recorded idle cash.
library SettlementLiquidityLib {
/// @dev LAYOUT-FROZEN: array elements have a fixed two-slot stride. Never append,
/// reorder or retype fields here; a later version needs a separate history.
struct Checkpoint {
uint64 at;
uint256 cumulative;
}
/// @custom:storage-location erc7201:forestroad.storage.SettlementLiquidity
struct State {
uint256 eligible; // Reviewed opening retained for migration evidence; later eligibility is derived.
bool initialized;
Checkpoint[] primary;
}
bytes32 private constant SETTLEMENT_LIQUIDITY_STORAGE_LOCATION =
0xd516499f8a4962dbaae5e8b618f43de5cd13920aac17c23e539a65240121de00;
error SettlementLiquidity_InvalidTime(uint256 timestamp);
function _state() private pure returns (State storage $) {
assembly {
$.slot := SETTLEMENT_LIQUIDITY_STORAGE_LOCATION
}
}
/// @notice Fresh zero history or one evidenced, conservative legacy opening allowance.
/// @dev Any remaining opening cash seasons from initialization; no later resnapshot exists.
function initialize(uint256 opening, uint256 idle, bytes32 evidence) public {
State storage s = _state();
if (s.initialized) revert IReserveManager.ReserveManager_SettlementLiquidityAlreadyInitialized();
if (opening > idle) revert IReserveManager.ReserveManager_InvalidSettlementOpening(opening, idle);
s.eligible = opening;
s.initialized = true;
_truncate(s.primary, 0);
emit IReserveManager.SettlementLiquidityInitialized(s.eligible, evidence);
_append(s.primary, idle - opening);
}
/// @notice Preserve the legacy selector only for books without the preliminary monitor.
function initializeLegacy(uint256 opening, uint256 idle, bytes32 evidence) public {
if (_state().initialized) revert IReserveManager.ReserveManager_SettlementLiquidityAlreadyInitialized();
if (_monitor().enabled) revert IReserveManager.ReserveManager_MonitoredOpeningRequired();
initialize(opening, idle, evidence);
}
/// @dev Read-only mirror of ReleaseHistoryMonitorLib.State (erc7201:forestroad.storage.ReleaseHistoryMonitor),
/// written only by the preliminary legacy reserve. Field order and packing must stay identical.
struct MonitorMirror {
bytes32 evidenceHash;
uint64 initializedBlock;
uint64 initializedAt;
bool enabled;
uint256 protectedRounding;
uint256 cashOutflows;
}
bytes32 private constant MONITOR_STORAGE_LOCATION =
0x6469194660fd363c0ee6c152feae78ade9d8b8e62a0f164628c9a3cae3830f00;
function _monitor() private pure returns (MonitorMirror storage $) {
assembly {
$.slot := MONITOR_STORAGE_LOCATION
}
}
/// @notice One-time legacy opening clamped from the frozen preliminary monitor in this proxy's storage.
/// @dev Outflows after the pin reduce the opening instead of refusing the release. Fresh inflows never
/// raise it. Returns the post-pin protected rounding for the host to record exactly once.
function initializeMonitored(IReserveManager.MonitoredOpening memory t, uint256 idle, bytes32 evidence)
public
returns (uint256 credit)
{
if (t.roundingCreditCap > 1e15) {
revert IReserveManager.ReserveManager_InvalidRoundingCreditCap(t.roundingCreditCap);
}
if (t.buffer != 50_000e18) revert IReserveManager.ReserveManager_InvalidOpeningBuffer(t.buffer);
if (t.selected > t.qualified) {
revert IReserveManager.ReserveManager_InvalidMonitoredSelection(t.selected, t.qualified);
}
MonitorMirror storage m = _monitor();
if (!m.enabled || m.evidenceHash != t.monitorEvidence || t.monitorEvidence == bytes32(0)) {
revert IReserveManager.ReserveManager_MonitorMismatch();
}
if (m.cashOutflows < t.pinnedCashOutflows) {
revert IReserveManager.ReserveManager_MonitorRegressed(t.pinnedCashOutflows, m.cashOutflows);
}
if (m.protectedRounding < t.pinnedProtectedRounding) {
revert IReserveManager.ReserveManager_MonitorRegressed(t.pinnedProtectedRounding, m.protectedRounding);
}
credit = m.protectedRounding - t.pinnedProtectedRounding;
if (credit > t.roundingCreditCap) {
revert IReserveManager.ReserveManager_RoundingCreditExceeded(credit, t.roundingCreditCap);
}
uint256 spent = m.cashOutflows - t.pinnedCashOutflows;
uint256 opening = t.qualified > spent ? t.qualified - spent : 0;
uint256 buffered = idle > t.buffer ? idle - t.buffer : 0;
if (buffered < opening) opening = buffered;
if (t.selected < opening) opening = t.selected;
emit IReserveManager.SettlementOpeningClamped(t.selected, t.qualified, spent, buffered, opening);
if (credit != 0) {
emit IReserveManager.PreReleaseRoundingCredited(t.pinnedProtectedRounding, m.protectedRounding, credit);
}
initialize(opening, idle, evidence);
}
/// @notice New primary claims cannot increase the current qualified balance.
function primaryDeposit(uint256 assets, uint256 idleAfter) public {
uint256 before_ = available(idleAfter - assets);
_append(_state().primary, assets);
emit IReserveManager.SettlementLiquidityAdjusted(before_, available(idleAfter));
}
/// @notice A measured protocol receipt is immediately qualified; it creates no pending primary lot.
function receipt(uint256 assets, uint256 idleAfter) public {
emit IReserveManager.SettlementLiquidityAdjusted(available(idleAfter - assets), available(idleAfter));
}
/// @notice Cash leaves newest unseasoned lots first, then qualified capital.
/// @dev Truncate the logical tail in one storage write; never loop over individual deposits.
function outflow(uint256 assets, uint256 idleAfter) public {
State storage s = _state();
uint256 before_ = available(idleAfter + assets);
uint256 pending = _pending(s.primary);
uint256 canceled = assets < pending ? assets : pending;
if (canceled != 0) {
uint256 target = s.primary[s.primary.length - 1].cumulative - canceled;
if (target == 0) {
_truncate(s.primary, 0);
} else {
uint256 low;
uint256 high = s.primary.length;
while (low < high) {
uint256 middle = low + (high - low) / 2;
if (s.primary[middle].cumulative < target) low = middle + 1;
else high = middle;
}
_truncate(s.primary, low + 1);
s.primary[low].cumulative = target;
}
emit IReserveManager.SettlementPrimaryCanceled(canceled);
}
emit IReserveManager.SettlementLiquidityAdjusted(before_, available(idleAfter));
}
/// @notice Qualified cash including seasoned primary cash; uninitialized legacy books return zero.
function available(uint256 idle) public view returns (uint256) {
State storage s = _state();
if (!s.initialized) return 0;
uint256 pending = _pending(s.primary);
return pending >= idle ? 0 : idle - pending;
}
/// @notice Current qualification and one-time initialization state.
function status(uint256 idle) public view returns (bool initialized, uint256 eligible) {
return (_state().initialized, available(idle));
}
function _pending(Checkpoint[] storage history) private view returns (uint256) {
uint256 count = history.length;
if (count == 0) return 0;
uint256 total = history[count - 1].cumulative;
if (block.timestamp < Config.DEFAULT_REDEEM_COOLDOWN) return total;
uint256 cutoff = block.timestamp - Config.DEFAULT_REDEEM_COOLDOWN;
uint256 low;
uint256 high = count;
while (low < high) {
uint256 middle = low + (high - low) / 2;
if (history[middle].at <= cutoff) low = middle + 1;
else high = middle;
}
uint256 mature = low == 0 ? 0 : history[low - 1].cumulative;
return total - mature;
}
function _append(Checkpoint[] storage history, uint256 assets) private {
if (assets == 0) return;
if (block.timestamp > type(uint64).max) revert SettlementLiquidity_InvalidTime(block.timestamp);
uint256 count = history.length;
uint256 total = count == 0 ? 0 : history[count - 1].cumulative;
if (count != 0 && history[count - 1].at > block.timestamp) {
revert SettlementLiquidity_InvalidTime(block.timestamp);
}
if (count != 0 && history[count - 1].at == block.timestamp) history[count - 1].cumulative = total + assets;
else history.push(Checkpoint(uint64(block.timestamp), total + assets));
emit IReserveManager.SettlementPrimaryRecorded(uint64(block.timestamp), assets);
}
function _truncate(Checkpoint[] storage history, uint256 length) private {
// Only an already checked prefix length reaches this helper. Discarded slots remain
// inaccessible and a future push explicitly overwrites every checkpoint field.
assembly ("memory-safe") {
sstore(history.slot, length)
}
}
}
src/interfaces/IReserveManager.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title IReserveManager
/// @notice Mainnet-v1 treasury for canonical USDC and deployed facility principal.
/// @dev USD values use 18 decimals. USDC amounts use the token's native 6 decimals.
interface IReserveManager {
/// @notice One-time settlement-liquidity initialization has already completed.
error ReserveManager_SettlementLiquidityAlreadyInitialized();
/// @notice An opening allowance cannot exceed the canonical recorded idle reserve.
error ReserveManager_InvalidSettlementOpening(uint256 opening, uint256 idle);
/// @notice Legacy opening allowance was independently reconciled to retained servicing cash.
event SettlementLiquidityInitialized(uint256 openingAssets, bytes32 indexed evidenceHash);
/// @notice A primary inflow begins its exact existing-cooldown qualification period.
event SettlementPrimaryRecorded(uint64 indexed at, uint256 assets);
/// @notice An outflow cancels newest unseasoned primary amounts without resetting older ages.
event SettlementPrimaryCanceled(uint256 assets);
/// @notice Reconstructable settlement-eligibility transition after a measured cash movement.
event SettlementLiquidityAdjusted(uint256 previous, uint256 current);
/// @notice Cash that may enlarge settlement budgets after primary inflows season through the existing cooldown.
function settlementLiquidity() external view returns (uint256);
/// @notice One-time legacy allowance; refuses once the preliminary monitor is enabled.
function initializeSettlementLiquidity(uint256 openingAssets, bytes32 evidenceHash) external;
/// @notice Pinned history terms for the monitored, execution-time-clamped legacy opening.
/// @dev Every value comes from the hash-bound history record and equals the release guard's immutables.
struct MonitoredOpening {
bytes32 monitorEvidence; // Permanent preliminary-monitor genesis commitment.
uint256 pinnedCashOutflows; // Monitor cashOutflows observed at the history pin.
uint256 pinnedProtectedRounding; // Monitor protectedRounding observed at the history pin.
uint256 qualified; // Conservative qualified-cash lower bound at the history pin.
uint256 selected; // Reviewed upper cap on the opening (at most `qualified`).
uint256 buffer; // Physical idle retained outside the opening.
uint256 roundingCreditCap; // Largest post-pin protected rounding credited; zero requires none.
}
/// @notice The legacy monitor at execution is absent, reset or not the one the history pinned.
error ReserveManager_MonitorMismatch();
/// @notice A monitor counter is below its pinned observation.
error ReserveManager_MonitorRegressed(uint256 pinned, uint256 current);
/// @notice Post-pin protected rounding exceeds the reviewed credit cap.
error ReserveManager_RoundingCreditExceeded(uint256 credit, uint256 cap);
/// @notice A monitored opening may credit at most 1e15 of protected rounding.
error ReserveManager_InvalidRoundingCreditCap(uint256 cap);
/// @notice The monitored opening must retain exactly the reviewed 50,000-USDfr buffer.
error ReserveManager_InvalidOpeningBuffer(uint256 buffer);
/// @notice A selected opening cannot exceed its independently qualified history.
error ReserveManager_InvalidMonitoredSelection(uint256 selected, uint256 qualified);
/// @notice An enabled preliminary monitor requires the clamped initialization path.
error ReserveManager_MonitoredOpeningRequired();
/// @notice The execution-time opening: min(selected, qualified - spent, idle - buffer).
event SettlementOpeningClamped(
uint256 selected, uint256 qualified, uint256 spentSincePin, uint256 bufferedIdle, uint256 opening
);
/// @notice Junior capital consumed by native rounding between the history pin and execution.
event PreReleaseRoundingCredited(uint256 pinned, uint256 current, uint256 credit);
/// @notice One-time governed legacy opening clamped at execution from the preliminary monitor.
/// @dev Opens min(selected, qualified - (cashOutflows - pinned), idle - buffer); never reverts on
/// outflows. Records post-pin protected rounding into this reserve's loss-protection record.
function initializeMonitoredSettlementLiquidity(MonitoredOpening calldata terms, bytes32 evidenceHash) external;
/// @notice Current qualified amount and initialization state for migration and monitoring.
function settlementLiquidityStatus() external view returns (bool initialized, uint256 eligible);
/// @notice Recognition or an opening import makes a return to legacy accounting unsafe.
error ReserveManager_LegacyRollbackUnsafe();
/// @notice Refuses a legacy-code rollback once accrual activation or migration has started.
/// @dev Read-only execution guard for a governance batch, not authority to upgrade.
function requireLegacyRollbackSafe() external view;
/// @notice Canonical USDC was pulled into recorded idle custody.
event USDCDeposited(address indexed from, uint256 requested, uint256 credited);
/// @notice Canonical USDC was released from recorded idle custody.
event USDCReleased(address indexed to, uint256 amount);
/// @notice A permissionless observation compared recorded and live USDC custody.
event IdleUSDCObserved(uint256 recorded, uint256 live, uint256 shortfall);
/// @notice An adjudicated custody loss reduced recorded idle backing.
event IdleUSDCWrittenDown(uint256 amount, uint256 remaining);
/// @notice Returned USDC was credited against one arm's written-down recovery capacity.
event RecoveredIdleUSDCCredited(
uint256 indexed armId, uint256 nativeUnits, uint256 value, bytes32 indexed evidenceHash
);
/// @notice A custody loss reduced backing and fixed the supply reduction the cascade must absorb.
event ReserveLossRecognized(
uint256 indexed incidentId, uint256 backingReduction, uint256 surplusAbsorbed, uint256 supplyReductionRequired
);
/// @notice The complete surplus-to-senior allocation of one recognized custody loss.
event ReserveLossAllocated(
uint256 indexed incidentId,
uint256 backingReduction,
uint256 surplusAbsorbed,
uint256 curatorAbsorbed,
uint256 backstopCovered,
uint256 seniorBurned,
uint256 residualDeficit
);
/// @notice The controller used for supply, backing, and loss-burn checks changed.
event LossControllerSet(address indexed previousController, address indexed newController);
/// @notice The ordered custody-cascade and governance timing modules were wired.
event ReserveLossModulesSet(
address indexed curator, address indexed backstop, address indexed vault, address governor, address timelock
);
/// @notice A Guardian created a persistent reserve-loss interlock and evidence commitment.
event ReserveLossArmed(uint256 indexed armId, uint256 indexed incidentId, bytes32 evidenceHash);
/// @notice Governance cancelled an unused arm and disabled future Guardian arms.
event ReserveLossArmCancelled(uint256 indexed armId, bytes32 indexed evidenceHash);
/// @notice Governance cancelled a custody false alarm while retaining all credit marks.
event UnratifiedReserveLossArmCancelled(
uint256 indexed armId, bytes32 indexed evidenceHash, uint256 retainedPrincipalImpairment
);
/// @notice A previously ratified arm must use the incident settlement path.
error ReserveManager_ArmAlreadyRatified(uint256 armId);
/// @notice Governance closed the arm-bound incident and disabled future Guardian arms.
event ReserveLossArmFinalized(uint256 indexed armId, uint256 indexed incidentId, bytes32 indexed evidenceHash);
/// @notice Governance ratified and executed the current objective custody shortfall.
event ReserveLossRatified(
uint256 indexed armId,
uint256 indexed incidentId,
uint256 approvedMaxLoss,
uint256 actualLoss,
bytes32 evidenceHash
);
/// @notice Governance enabled or disabled creation of new Guardian reserve-loss arms.
event GuardianReserveLossArmsEnabled(bool enabled);
/// @notice A custody-loss incident entered the active register under its bound arm.
event ReserveLossIncidentOpened(uint256 indexed incidentId, uint256 indexed armId, bytes32 evidenceHash);
/// @notice The active custody-loss incident left the register.
event ReserveLossIncidentClosed(uint256 indexed incidentId);
/// @notice A cascade changed the latched unabsorbed reserve deficit.
event ReserveDeficitUpdated(uint256 indexed incidentId, uint256 previousDeficit, uint256 currentDeficit);
/// @notice Governance cleared a cured reserve-deficit latch with supporting evidence.
event ReserveDeficitResolved(uint256 previousDeficit, bytes32 evidenceHash);
/// @notice Idle USDC became deployed principal for a facility.
event PrincipalDeployed(uint256 indexed facilityId, uint256 amount);
/// @notice A retained origination fee became additional facility principal.
event FeeCapitalized(uint256 indexed facilityId, uint256 amount);
/// @notice Contractually accrued PIK interest joined a facility's deployed principal.
/// @dev No cash moved and, unlike `FeeCapitalized`, none was retained either.
/// @param facilityId The facility.
/// @param amount 18-decimal value capitalised.
/// @param deployedAfter The facility's deployed principal after the act.
event PikCapitalized(uint256 indexed facilityId, uint256 amount, uint256 deployedAfter);
/// @notice A cash receipt increased idle custody and reduced the stated principal leg.
event PaymentReceived(
uint256 indexed facilityId, address indexed payer, uint256 usdcAmount, uint256 principalReturned
);
/// @notice Realized facility principal was removed from backing.
event PrincipalWrittenDown(uint256 indexed facilityId, uint256 amount);
/// @notice Governance added an evidence-backed conservative facility impairment.
event PrincipalImpairmentRecognized(
uint256 indexed facilityId,
uint256 amount,
uint256 facilityImpairment,
uint256 totalImpairment,
uint256 backingAfter,
bytes32 evidenceHash
);
/// @notice Governance released part of an evidence-backed conservative facility impairment.
event PrincipalImpairmentReleased(
uint256 indexed facilityId,
uint256 amount,
uint256 facilityImpairment,
uint256 totalImpairment,
bytes32 evidenceHash
);
/// @notice A principal write-down consumed the corresponding previously recognized impairment.
event PrincipalImpairmentRealized(
uint256 indexed facilityId, uint256 amount, uint256 facilityImpairment, uint256 totalImpairment
);
/// @notice The retained compatibility loss-absorber binding changed.
event LossAbsorberSet(address indexed previousAbsorber, address indexed newAbsorber);
/// @notice A funder supplied new canonical USDC backing without minting claims.
event Recapitalized(
address indexed funder, uint256 units, uint256 credited, uint256 backingAfter, uint256 deficitOutstanding
);
/// @notice A senior-exit junior draw was added to the historical prepayment ledger.
event ExitPrepaymentRecorded(uint256 amount, uint256 outstanding);
/// @notice A facility loss consumed part of the historical exit-prepayment ledger.
event ExitPrepaymentConsumed(uint256 indexed facilityId, uint256 consumed, uint256 outstanding);
/// @notice A custody loss consumed the surplus backing part of an exit prepayment.
event ExitPrepaymentAbsorbedByCustody(uint256 indexed incidentId, uint256 consumed, uint256 outstanding);
/// @notice Governance permanently bound the borrower-payout policy used before USDC deployment.
event BorrowerPayoutRegistrySet(address indexed registry);
/// @notice Requested USDC value exceeds recorded idle value.
error ReserveManager_InsufficientIdleValue(uint256 requestedValue, uint256 idleValue);
/// @notice Requested principal reduction exceeds the facility's live deployed principal.
error ReserveManager_InsufficientDeployedPrincipal(uint256 facilityId, uint256 requested, uint256 deployed);
/// @notice A value-moving call supplied a zero amount.
error ReserveManager_ZeroAmount();
/// @notice A required account or module address is zero.
error ReserveManager_ZeroAddress();
/// @notice The caller is not an authorised controller or credit depositor.
error ReserveManager_NotDepositor(address caller);
/// @notice A pull expected canonical USDC but received no value.
error ReserveManager_NoValueReceived();
/// @notice The token balance delta differed from the requested USDC transfer.
error ReserveManager_UnexpectedUSDCReceipt(uint256 expected, uint256 received);
/// @notice A legacy idle write-down exceeds recorded idle value.
error ReserveManager_WriteDownExceedsIdle(uint256 amount, uint256 idle);
/// @notice A USDC release or deployment attempted to target the ReserveManager itself.
error ReserveManager_SelfDeployment();
/// @notice An 18-decimal value cannot be represented exactly in native USDC units.
error ReserveManager_ValueNotUSDCExact(uint256 value);
/// @notice The configured custody token does not use canonical USDC's six decimals.
error ReserveManager_InvalidUSDCDecimals(uint8 decimals);
/// @notice A payment allocated more principal than the USDC value actually received.
error ReserveManager_PrincipalExceedsPayment(uint256 principal, uint256 paymentValue);
/// @notice A proposed curator, backstop, vault, or absorber fails its binding contract.
error ReserveManager_InvalidLossAbsorber(address absorber);
/// @notice A proposed controller fails its module and reserve binding contract.
error ReserveManager_InvalidLossController(address controller);
/// @notice A loss layer's reported burn differs from the observed USDfr supply reduction.
error ReserveManager_LossAbsorberContractViolated(uint256 backingReduction, uint256 supplyBurned);
/// @notice Reported cascade allocation does not reconcile to the recognized loss.
error ReserveManager_LossAllocationMismatch(
uint256 expectedSurplus, uint256 reportedSurplus, uint256 expectedAccounted, uint256 reportedAccounted
);
/// @notice The terminal live supply/backing deficit differs from the cascade calculation.
error ReserveManager_PostLossDeficitMismatch(uint256 expectedDeficit, uint256 observedDeficit);
/// @notice A custody incident id has already been consumed.
error ReserveManager_IncidentAlreadyUsed(uint256 incidentId);
/// @notice A new arm or incident cannot replace the currently active incident.
error ReserveManager_IncidentAlreadyActive(uint256 incidentId);
/// @notice A terminal action requires an active custody incident.
error ReserveManager_NoActiveIncident();
/// @notice The supplied custody incident does not match the active incident.
error ReserveManager_IncidentMismatch(uint256 expected, uint256 supplied);
/// @notice The caller lacks the reserve-administration authority required for the live loss path.
error ReserveManager_ReserveLossCallerNotAdmin(address caller);
/// @notice A reserve-loss allocation used an id outside the custody-event namespace.
error ReserveManager_InvalidReserveLossIncident(uint256 incidentId);
/// @notice A cascade was requested without a recognized supply reduction.
error ReserveManager_NoRecognizedReserveLoss();
/// @notice Finalization was attempted while recognized loss remains unallocated.
error ReserveManager_RecognizedLossOutstanding(uint256 amount);
/// @notice Finalization was attempted while live USDC custody remains short.
error ReserveManager_LiveShortfallExists(uint256 nativeUnits);
/// @notice Finalization was attempted while supply still exceeds backing.
error ReserveManager_DeficitStillExists(uint256 recordedDeficit, uint256 observedDeficit);
/// @notice Creation of new Guardian reserve-loss arms is disabled.
error ReserveManager_GuardianArmsDisabled();
/// @notice A new arm cannot replace the currently active arm.
error ReserveManager_ArmAlreadyActive(uint256 armId);
/// @notice An arm-bound action requires an active arm.
error ReserveManager_NoActiveArm();
/// @notice The supplied arm id does not match the active arm.
error ReserveManager_ArmMismatch(uint256 expected, uint256 supplied);
/// @notice Ratification evidence does not match the Guardian's armed commitment.
error ReserveManager_ArmEvidenceMismatch(bytes32 expected, bytes32 supplied);
/// @notice The monotonic arm id space is exhausted.
error ReserveManager_ArmIdExhausted();
/// @notice Ratification found that the objective custody shortfall was already cured.
error ReserveManager_ShortfallCured();
/// @notice The live custody loss exceeds governance's approved maximum.
error ReserveManager_LossExceedsApproval(uint256 actualLoss, uint256 approvedMaxLoss);
/// @notice No physically returned USDC is available for the supplied arm.
error ReserveManager_NoRecoveredUSDC(uint256 armId);
/// @notice Finalization found returned USDC that has not yet been credited.
error ReserveManager_RecoveredUSDCNotCredited(uint256 armId, uint256 nativeUnits);
/// @notice The superseded arbitrary idle-write-down entry is permanently disabled.
error ReserveManager_LegacyPathDisabled();
/// @notice Cancellation would release an interlock while a loss condition remains live.
error ReserveManager_InterlockReleaseForbidden();
/// @notice Loss-module rebinding is forbidden while an arm, incident, shortfall, or deficit is live.
error ReserveManager_ModuleRebindForbidden();
/// @notice The proposed governor and timelock do not expose one coherent live timing path.
error ReserveManager_InvalidGovernanceTiming(address governor, address timelock);
/// @notice An evidence-backed transition supplied the zero evidence hash.
error ReserveManager_ZeroEvidenceHash();
/// @notice A conservative impairment would exceed the facility's remaining face principal.
error ReserveManager_ImpairmentExceedsFace(uint256 facilityId, uint256 requested, uint256 remainingFace);
/// @notice An impairment release exceeds the amount currently recognized for the facility.
error ReserveManager_ImpairmentReleaseExceedsRecognized(uint256 facilityId, uint256 requested, uint256 recognized);
/// @notice The caller is not the retained compatibility loss absorber.
error ReserveManager_NotLossAbsorber(address caller);
/// @notice Recorded idle USDC exceeds live custody, so a protected out-door is closed.
error ReserveManager_IdleCustodyShortfall(uint256 recordedUnits, uint256 liveUnits);
/// @notice A legacy incident nonce is zero or enters the reserved custody namespace.
error ReserveManager_InvalidIncidentNonce(uint256 incidentNonce);
/// @notice Deficit resolution was requested without a recorded deficit.
error ReserveManager_NoReserveDeficit();
/// @notice An incident close requires its recorded deficit to be resolved first.
error ReserveManager_DeficitResolutionRequired(uint256 recordedDeficit);
/// @notice The borrower-payout policy was already bound and cannot be replaced.
error BorrowerPayout_RegistryAlreadySet(address registry);
/// @notice A proposed borrower-payout policy has no compatible code.
error BorrowerPayout_InvalidRegistry(address registry);
/// @notice Loan proceeds may not be directed to this address.
error BorrowerPayout_RecipientNotAllowed(address recipient);
/// @notice Pulls exact canonical USDC from `from` into recorded idle custody.
function depositUSDC(address from, uint256 amount) external returns (uint256 credited);
/// @notice Releases recorded idle USDC through the controller-only redemption path.
function releaseUSDC(address to, uint256 amount) external;
/// @notice Permanently binds the timelock-managed borrower-payout registry.
function setBorrowerPayoutRegistry(address registry) external;
/// @notice The permanent borrower-payout policy, or zero before the required binding.
function borrowerPayoutRegistry() external view returns (address);
/// @notice Permissionlessly checkpoints the objective live-vs-recorded custody shortfall.
/// @dev Observation never changes backing and never moves junior or senior capital.
/// @return shortfall Native six-decimal USDC units missing from custody.
function reconcileIdleUSDC() external returns (uint256 shortfall);
/// @notice Permissionless live-vs-recorded custody observation; never changes accounting.
function observeIdleUSDC() external view returns (uint256 recorded, uint256 live, uint256 shortfall);
/// @notice Native USDC units by which recorded idle custody exceeds the live token balance.
function idleCustodyShortfall() external view returns (uint256);
/// @notice Recorded backing net of any physically observable idle-custody shortfall.
function recognizedBackingValue() external view returns (uint256);
/// @notice Whether an arm, incident, recognized loss, deficit, or live shortfall locks exits.
function custodyLossUnabsorbed() external view returns (bool);
/// @notice Wires the controller used for direct supply/backing and loss-burn checks.
function setLossController(address controller) external;
/// @notice Wires the retained compatibility absorber after verifying its reserve binding.
function setLossAbsorber(address absorber) external;
/// @notice Legacy incident controls retained as non-credit compatibility surfaces while
/// new custody accounting uses the arm-bound ratification path.
function openReserveLossIncident(uint256 incidentNonce, bytes32 evidenceHash)
external
returns (uint256 incidentId);
/// @notice Closes the exact active legacy incident once no deficit remains.
function closeReserveLossIncident(uint256 incidentId) external;
/// @notice Clears a cured legacy reserve-deficit latch with supporting evidence.
function resolveReserveDeficit(bytes32 evidenceHash) external;
/// @notice Canonical USDC held above the amount recorded as idle custody.
function unrecordedUSDC() external view returns (uint256);
/// @notice Wires the ordered custody cascade and its live governance timing sources.
function setReserveLossModules(address curator, address backstop, address vault, address governor, address timelock)
external;
/// @notice Guardian-only persistent interlock created before an amount-bearing proposal.
/// @return armId Monotonic internal id consumed only by an explicit governance terminal action.
/// @return incidentId Structurally bound upper-half custody event id.
function armReserveLossFreeze(bytes32 evidenceHash) external returns (uint256 armId, uint256 incidentId);
/// @notice Governance consumes an unused arm only when the objective shortfall is zero and
/// no adjudicated loss, incident or deficit exists; future Guardian arms stay disabled.
function cancelAndDisable(uint256 expectedArmId, bytes32 evidenceHash) external;
/// @notice Cancels an unratified custody false alarm and disables further guardian arms.
/// @dev Requires accounted custody and no unsettled custody incident or reserve deficit.
/// Independent credit impairment and exit prepayments remain unchanged.
/// @param expectedArmId Exact active arm being cancelled.
/// @param evidenceHash Nonzero commitment to the governance resolution evidence.
function cancelUnratifiedArm(uint256 expectedArmId, bytes32 evidenceHash) external;
/// @notice Governance kill switch for repeated Guardian arms.
function setGuardianReserveLossArmsEnabled(bool enabled) external;
/// @notice Governance ratifies and atomically absorbs the live objective shortfall, bounded
/// by the amount approved in the proposal. Every tranche under an arm reuses its id
/// and must supply the Guardian's exact armed evidence commitment.
function ratifyAndOpen(uint256 expectedArmId, bytes32 evidenceHash, uint256 approvedMaxLoss)
external
returns (uint256 incidentId, uint256 actualLoss);
/// @notice Credits physically returned canonical USDC without minting USDfr, capped by the
/// amount previously written down under `armId`. May execute after incident closure.
function creditRecoveredIdleUSDC(uint256 armId, bytes32 evidenceHash) external returns (uint256 credited);
/// @notice Atomically resolves a cured deficit, closes the arm-bound incident and disables
/// future Guardian arms. It cannot release a shortfall or uncredited returned USDC.
function finalizeAndDisable(uint256 expectedArmId, bytes32 evidenceHash) external;
/// @notice Pulls new canonical USDC backing without minting USDfr claims.
function recapitalize(uint256 amount) external returns (uint256 credited);
/// @notice Controller used for supply, backing, and loss-burn verification.
function lossController() external view returns (address);
/// @notice Ordered curator, backstop, vault, governor, and timelock bindings.
function reserveLossModules()
external
view
returns (address curator, address backstop, address vault, address governor, address timelock);
/// @notice Active custody incident id and its evidence commitment.
function activeReserveLossIncident() external view returns (uint256 incidentId, bytes32 evidenceHash);
/// @notice Whether a custody incident id has already entered the durable register.
function reserveLossIncidentUsed(uint256 incidentId) external view returns (bool);
/// @notice Latched portion of adjudicated custody losses not absorbed by any capital layer.
function reserveDeficit() external view returns (uint256);
/// @notice Current recognized backing reduction and pending cascade requirement.
function recognizedReserveLoss()
external
view
returns (uint256 backingReduction, uint256 surplusAbsorbed, uint256 supplyReductionRequired);
/// @notice Active arm identity, derived incident, armed evidence, and future-arm switch.
function reserveLossArm()
external
view
returns (uint256 armId, uint256 incidentId, bytes32 evidenceHash, bool armsEnabled);
/// @notice Native USDC recovery capacity created by write-downs under one arm.
function reserveLossRecoveryCapacity(uint256 armId) external view returns (uint256 nativeUnits);
/// @notice Retained compatibility absorber bound to this reserve.
function lossAbsorber() external view returns (address);
/// @notice Historical junior prepayment still available for impairment release.
function exitPrepaidAbsorption() external view returns (uint256);
/// @notice Records a senior-exit junior draw in the compatibility prepayment ledger.
function recordExitPrepayment(uint256 amount) external;
/// @notice Consumes prepayment only against recognized impairment for a facility loss.
function consumeExitPrepayment(uint256 facilityId, uint256 loss) external returns (uint256 used);
/// @notice Shared fail-closed interlock consumed by curator withdrawals and queue settlement.
function reserveLossExitsLocked() external view returns (bool);
/// @notice Backwards-compatible semantic alias used by CuratorModule.
function curatorWithdrawalsLocked() external view returns (bool);
/// @notice Converts exact recorded idle USDC into deployed facility principal.
function recordDeployment(uint256 facilityId, address to, uint256 usdcAmount) external;
/// @notice Adds retained origination-fee cash as facility principal without moving custody.
function recordFeeCapitalization(uint256 facilityId, uint256 amount) external;
/// @notice Capitalises accrued PIK interest into a facility's deployed principal. No cash moves.
/// @dev CREDIT_ROLE, and in practice `WaterfallEngine.capitalizePik` alone, which carries every
/// bound. See `ReserveManager.recordPikCapitalization` for why there is no idle check.
/// @param facilityId The facility.
/// @param amount 18-decimal value to capitalise, exact on the USDC grid.
function recordPikCapitalization(uint256 facilityId, uint256 amount) external;
/// @notice Atomically pulls exact USDC and accounts the principal leg.
function recordPayment(uint256 facilityId, address payer, uint256 usdcAmount, uint256 principal)
external
returns (uint256 receivedValue);
/// @notice Removes realized facility principal and consumes its corresponding impairment.
function recordPrincipalWritedown(uint256 facilityId, uint256 amount) external;
/// @notice Records an evidence-backed conservative mark without moving face principal or
/// allocating the loss between capital layers.
function recognizePrincipalImpairment(uint256 facilityId, uint256 amount, bytes32 evidenceHash) external;
/// @notice Reverses a conservative mark, bounded by the amount previously recognized.
function releasePrincipalImpairment(uint256 facilityId, uint256 amount, bytes32 evidenceHash) external;
/// @notice Recorded idle custody expressed as 18-decimal USDfr value.
function idleReserve() external view returns (uint256);
/// @notice Recorded idle custody in native six-decimal USDC units.
function idleUSDC() external view returns (uint256);
/// @notice Aggregate deployed facility principal before conservative impairments.
function deployedPrincipal() external view returns (uint256);
/// @notice Aggregate evidence-backed conservative principal impairment.
function totalPrincipalImpairment() external view returns (uint256);
/// @notice Evidence-backed conservative impairment recorded for one facility.
function principalImpairmentOf(uint256 facilityId) external view returns (uint256);
/// @notice Recorded idle plus deployed principal, net of conservative impairments.
function totalBackingValue() external view returns (uint256);
/// @notice Outstanding receivable face deployed to one facility.
/// @dev Continuous accrual includes earned but unreceived cash and PIK interest.
function deployedTo(uint256 facilityId) external view returns (uint256);
/// @notice Canonical six-decimal USDC token held by the reserve.
function usdc() external view returns (address);
/// @notice Converts native six-decimal USDC units to 18-decimal protocol value.
function normalizeUSDC(uint256 amount) external pure returns (uint256);
/// @notice Converts exact 18-decimal protocol value to native USDC units.
function denormalizeUSDC(uint256 value) external pure returns (uint256);
}
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.