Verified contractExactBUSL-1.1
CuratorModule
Address0xb664177b2ff9c3b617e68d638ca725845faf02fb
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.30
- Same code
Only this contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 100 runs
- EVM version
- cancun
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,486,092
- Creation transaction
- 0xee950c17fc…74f8f113f7
37 files
- src/CuratorModule.solmain107.24 KB
- lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol8.33 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol9.28 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol6.57 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol1.19 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol3.66 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol4.51 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol1.15 KB
- lib/openzeppelin-contracts/contracts/access/IAccessControl.sol3.34 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol193 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol637 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol182 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol12.18 KB
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol882 B
- lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol6.24 KB
- lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol473 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol10.08 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6 KB
- lib/openzeppelin-contracts/contracts/utils/Errors.sol896 B
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4.18 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol32.15 KB
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- src/interfaces/ICollateralRegistry.sol21.89 KB
- src/interfaces/IConservativeImpairmentBook.sol3.16 KB
- src/interfaces/ICuratorModule.sol22.46 KB
- src/interfaces/IGovernanceSchedule.sol2.33 KB
- src/interfaces/IPointsModule.sol2.43 KB
- src/interfaces/IReserveManager.sol31.28 KB
- src/interfaces/IsUSDfr.sol14.06 KB
- src/libraries/Config.sol23.1 KB
- src/libraries/PointsHookGas.sol3.99 KB
- src/libraries/Roles.sol4.2 KB
src/CuratorModule.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {ICollateralRegistry} from "./interfaces/ICollateralRegistry.sol";
import {IConservativeImpairmentBook} from "./interfaces/IConservativeImpairmentBook.sol";
import {ICuratorModule} from "./interfaces/ICuratorModule.sol";
import {IGovernanceSchedule, ITimelockSchedule} from "./interfaces/IGovernanceSchedule.sol";
import {IPointsModule} from "./interfaces/IPointsModule.sol";
import {IReserveManager} from "./interfaces/IReserveManager.sol";
import {IsUSDfr} from "./interfaces/IsUSDfr.sol";
import {Config} from "./libraries/Config.sol";
import {PointsHookGas} from "./libraries/PointsHookGas.sol";
import {Roles} from "./libraries/Roles.sol";
/// @title CuratorModule — per-class curator first-loss vaults (ADR-0004)
/// @notice Cascade LAYER 1 (CLAUDE.md §1.3 ordering): curator capital absorbs realized
/// losses before the sGROVE backstop and before any depositor impairment.
/// Each collateral class has its own USDfr pool; multiple curators in a class
/// hold internal shares so partial absorptions dilute all of them exactly
/// pro-rata. A fully wiped pool advances to a new share round: stale-round
/// shares are worth zero and are cleared lazily on the holder's next post.
///
/// SUBORDINATION HEADROOM: capital protecting live exposure cannot leave —
/// withdrawals are capped at `poolBalance - requiredFirstLoss(classId)`, where the
/// requirement is `max(min(firstLossTarget, classExposure), declaredDefaulted + pastDue)`.
/// AUDIT FIX (SWEEP-2 CSG-F1): the second term is NOT decoration. Until it was added this
/// line read `poolBalance - min(firstLossTarget, classExposure)` and was FALSE — the
/// conservative senior NAV credits layer 1 at `min(declared + pastDue, poolBalance)`, so
/// on any class whose exposure exceeds its target a curator could withdraw capital the
/// senior redemption price was already extending credit for. See `_requiredFirstLoss`.
/// Curators earn nothing here; their return comes from origination economics.
/// Senior (`sUSDfr`) is therefore never subordinated to this junior capital.
///
/// TWO INDEPENDENT WITHDRAWAL FREEZES, one per loss path. Headroom alone is not
/// enough: it is a LEVEL check against live exposure and says nothing about a loss
/// already in flight. R4-EC2 freezes a class on a FACILITY default
/// (`unresolvedDefaults`, armed by `freezeOnDefault`); R6-CF1 freezes ALL classes
/// while a reserve-CUSTODY loss is recognised, observable or incompletely absorbed
/// (`custodyFreezeActive`, derived from the ReserveManager plus an optional guardian
/// pre-arm). Neither substitutes for the other, and removing either re-opens a
/// curator's ability to exit ahead of a loss it is layer 1 for.
/// @dev `absorbLoss` is deliberately NOT pausable: the guardian can halt curator
/// post/withdraw traffic, but never the loss cascade — a paused cascade during a
/// credit event would block honest loss recognition (CLAUDE.md fail-loudly).
contract CuratorModule is
Initializable,
AccessControlUpgradeable,
PausableUpgradeable,
ReentrancyGuardUpgradeable,
UUPSUpgradeable,
ICuratorModule
{
using SafeERC20 for IERC20;
/// @notice The largest share/balance ratio a class pool may carry before `postFirstLoss`
/// treats it as WIPED and starts a fresh round (AUDIT FIX SWEEP-3 S3-F1).
/// @dev 1e18 = a share price of 1e-18, i.e. one share worth less than the smallest
/// representable unit of an 18-decimal token. See the block in `postFirstLoss` for why
/// this constant exists, what it bounds, and why lowering it back to "exact zero" (which
/// is what any value above 1e18 approaches) re-opens a permissionless liveness brick on
/// cascade layer 1. Below 1e18 outstanding shares this reduces EXACTLY to the shipped
/// `balance == 0` predicate, so it is strictly a widening.
uint256 internal constant MAX_SHARE_INFLATION = 1e18;
/// @notice AUDIT FIX (SWEEP-4 S4-R1). How many CLOSED rounds one call will walk a stale stake
/// through. See `_settleStaleRound` for why the walk exists, why it must be bounded,
/// and why a bound is not a loss: `claimClosedRound` keeps the progress of every hop it
/// makes, so a chain longer than this is recovered by calling it again.
/// @dev Each hop requires a class's layer-1 pool to have been driven to a share price of 1e-18
/// or below and then recapitalised, so 32 unclaimed closes on one stake is far outside any
/// operational scenario; the bound exists to keep worst-case gas finite on the very
/// recapitalisation path S3-F1 exists to protect, not because 32 is expected to bind.
uint256 private constant MAX_CLOSED_ROUND_HOPS = 32;
/// @dev Loss notifications append one class epoch and ratio, without historical traversal.
/// A cold first loss measures 97,223 gas; 200k retains headroom for that constant work.
uint256 private constant LOSS_POINTS_HOOK_GAS = 200_000;
/// @dev Kept outside the optional loss CALL for fixed telemetry and the reentrancy epilogue.
uint256 private constant POINTS_HOOK_EPILOGUE_GAS = 30_000;
/// @dev Each remaining global-loss iteration can skip its observer and emit bounded telemetry.
uint256 private constant POINTS_HOOK_ITERATION_GAS = 10_000;
/// @dev Covers call setup and EIP-150 bookkeeping after the loss allowance is measured.
uint256 private constant POINTS_HOOK_CALL_PREPARATION_GAS = 5_000;
struct ClassPool {
uint256 balance; // USDfr actually held for this class
uint256 totalShares; // internal pro-rata shares over `balance`
uint256 round; // advances when a pool is wiped to zero with shares outstanding
// Cumulative power-of-two reduction applied to share units in this round.
// Appended for upgrade safety; zero is the legacy scale.
uint256 shareScale;
}
struct CuratorStake {
uint256 shares;
uint256 round; // shares are valid only while round == pool.round
// Scale at the last write to this stake; conversion is lazy and rounds down.
uint256 shareScale;
}
/// @notice AUDIT FIX (SWEEP-4 S4-R1). The residual-claim snapshot taken when a round is CLOSED
/// as economically wiped while a non-zero balance still stands.
/// @dev It is a pure CONVERSION RATE, not a pot of money. At the close the new round opens with
/// `totalShares == balance` (share price exactly 1) and those shares are minted with NO
/// owner; this snapshot records who owns them. `carriedShares` therefore stays inside
/// `pool.totalShares` and inside `pool.balance` for the whole of its life, which is what
/// makes the residual keep absorbing as cascade layer 1 exactly as it did before the close.
/// Both fields are decremented on each settlement, so the remaining holders always divide
/// the remaining carried shares — the standard remaining/remaining form, exact under
/// floor division with the dust favouring the pool.
struct ClosedRound {
uint256 shares; // unsettled shares OF the closed round (the denominator)
uint256 carriedShares; // unclaimed shares of round+1, expressed at carriedScale
// Lazy share-scale normalization is aggregate state. Record the scale at the close so a
// stale stake written before a later normalization is converted into this snapshot's
// units before the remaining/remaining division.
uint256 shareScale;
// A later pool normalization divides totalShares. The unclaimed aggregate must be
// divided ONCE before any holder takes from it; dividing each claim separately with
// a ceiling can distribute more shares than the normalized pool contains.
// Existing snapshots have zero here and are interpreted in original shareScale
// until first touched. Pre-upgrade snapshots already overallocated by prior
// settlement require a separate state inventory before an upgrade.
uint256 carriedScale;
}
/// @custom:storage-location erc7201:forestroad.storage.CuratorModule
struct CuratorStorage {
IERC20 usdfr;
ICollateralRegistry registry;
mapping(uint256 classId => ClassPool) pools;
mapping(uint256 classId => mapping(address curator => CuratorStake)) stakes;
mapping(uint256 classId => mapping(address curator => bool)) approved;
mapping(uint256 classId => uint256) targets; // first-loss target (ADR-0004)
// AUDIT FIX (R4-EC2): per-class count of unresolved defaults. Non-zero freezes
// curator withdrawals so a curator cannot front-run realizeLoss to pull excess
// first-loss ahead of a loss it should absorb. Incremented by the DefaultManager
// on default entry (declareDefault / liquidate), decremented by governance on
// workout resolution. (Append-only: added at the tail for upgrade safety.)
mapping(uint256 classId => uint256) unresolvedDefaults;
// AUDIT FIX (P-01): participation-points hook. First-loss capital accrues points at
// the curator multiple (in lieu of only earning origination economics). Optional;
// fail-open so a points failure can never block first-loss post/withdraw.
IPointsModule pointsModule;
// Vault fee-accounting coordinator. Brackets capacity writes so a curator
// top-up/withdrawal cannot be mistaken for senior investment performance.
IsUSDfr feeVault;
// ── AUDIT FIX (R6-CF1) tail: the reserve-CUSTODY arm of the withdrawal freeze ─────
// APPEND-ONLY TAIL. These four fields MUST stay last and MUST NOT be reordered, retyped
// or moved: `CuratorModule` sits behind a live UUPS proxy and everything above is already
// written on-chain. `tools/check-storage-layout.mjs` and
// `tools/check-compiled-storage-layout.mjs` both enforce this.
//
// WHY THEY EXIST (do not delete): R4-EC2 froze withdrawals on a FACILITY default, and the
// only writer of `unresolvedDefaults` is `DefaultManager.freezeOnDefault`. The
// reserve-CUSTODY loss path armed nothing, so a curator could pull every dollar of
// headroom between an adjudicated custody incident being recognised and its write-down
// executing — handing a loss that curator capital is LAYER 1 for straight to the sGROVE
// backstop and senior depositors. `reserves` is the source of the derived freeze predicate;
// `governor` supplies the live governance-path length the guardian pre-arm must outlast.
IReserveManager reserveManager;
address governor;
uint64 custodyPreArmExpiry;
uint32 custodyPreArmCount;
// ── AUDIT FIX (SWEEP-4 S4-R1) tail: closed-round residual claims ──────────────────────
// APPEND-ONLY TAIL, SAME RULE AS THE R6-CF1 BLOCK ABOVE: this mapping MUST stay last and
// MUST NOT be reordered or retyped. Both storage-layout gates enforce it.
//
// WHY IT EXISTS (do not delete): SWEEP-3 S3-F1 fixed a real liveness brick by closing a
// round once the share price falls to or below 1e-18, and it forfeited the residual
// `balance` to the pool as UNOWNED backing. Its NatSpec bounds that forfeiture as dust on
// the assumption that the share price is near 1. It is not: `totalShares` is not bounded by
// the balance, because a post made while the price is ALREADY collapsed mints
// `mulDiv(amount, totalShares, balance)` shares. MEASURED on the shipped tree
// (`SweepR4_CuratorClosedRounds`): after one such ordinary recapitalisation a
// 0.999e18 loss closed the round and destroyed a 1_000e18 curator claim — a thousandfold
// amplification of the loss the cascade actually took, on the permissionless ADR-0034 Y-bis
// draw path. This mapping is what carries that claim across the close.
mapping(uint256 classId => mapping(uint256 round => ClosedRound)) closedRounds;
}
// keccak256(abi.encode(uint256(keccak256("forestroad.storage.CuratorModule")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant CURATOR_STORAGE_LOCATION =
0x3ed45dc5309d95eb5c32609ee7ca79f82c5062e7efdb606949190d8a38c9b400;
/// @notice AUDIT FIX (F3-PA-c) — THE BOUND THE PRE-ARM DURATION IS DERIVED FROM. Ceiling on the
/// governance path `custodyPreArmDuration()` will honour. Governance can set
/// `votingDelay`/`votingPeriod`/`minDelay` to arbitrary values, so without a bound a
/// retuned parameter (or an overflowing sum) could turn a guardian pre-arm into an
/// unbounded lock on curator capital.
///
/// DO NOT CHANGE ONE OF THESE TWO CONSTANTS WITHOUT THE OTHER. The pre-arm's stated
/// requirement is that it strictly EXCEED the governance path it was derived from.
/// R6-CF1 shipped the cap on the DURATION only, and each of the three terms capped at
/// `CUSTODY_PRE_ARM_MAX_DURATION` — so a path of up to 3 x 90 days could be summed and
/// then silently truncated to a 90-day window, INVERTING the requirement stated in
/// `custodyPreArmDuration`'s own NatSpec with no signal of any kind. The cap now binds
/// on the PATH, and `CUSTODY_PRE_ARM_MAX_DURATION == CUSTODY_PRE_ARM_MAX_PATH * 3 / 2`
/// EXACTLY, which makes the duration clamp provably non-binding and the
/// "duration > bounded path" property structural rather than incidental. Beyond
/// `CUSTODY_PRE_ARM_MAX_PATH` the cap does still bind — but never silently: see
/// `custodyPreArmCoversLiveGovernancePath` and the `CustodyFreezePreArmTruncated`
/// event, and `script/Validate.s.sol`, which refuses a deployment whose pre-arm no
/// longer OUTLASTS the live path.
///
/// P-49 — BE PRECISE HERE, THE TWO CONDITIONS ARE NOT THE SAME. The cap binding is
/// not by itself a refusal. Once the path exceeds `CUSTODY_PRE_ARM_MAX_PATH` the
/// derived duration pins at `CUSTODY_PRE_ARM_MAX_DURATION` (90 days), which still
/// outlasts any live path below 90 days. So for a live path in
/// (60 days, 90 days) the cap BINDS and coverage still HOLDS; refusal begins at a
/// live path of 90 days, where duration ceases to exceed it. This block previously
/// claimed a deployment was refused wherever the cap binds, and the validator did
/// not check either condition — see P-49.
uint64 public constant CUSTODY_PRE_ARM_MAX_PATH = 60 days;
/// @notice AUDIT FIX (R6-CF1). Ceiling on one guardian pre-arm. Equal to
/// `CUSTODY_PRE_ARM_MAX_PATH * 3 / 2` by construction — see the note above.
uint64 public constant CUSTODY_PRE_ARM_MAX_DURATION = 90 days;
/// @dev AUDIT FIX (SWEEP-2 CSG-F1). The fail-closed sentinel `_markedFirstLoss` returns when
/// the wired loss absorber cannot answer `declaredDefaultedPrincipal`/`pastDuePrincipal`.
/// `type(uint128).max` is ~3.4e38 USDfr: unreachably above any pool balance (USDfr's
/// supply is bounded by the reserve's USDC backing), so `_headroom` floors to zero and
/// every withdrawal is refused, while `requiredFirstLoss()` publishes an obviously
/// sentinel value rather than reverting. DO NOT lower it to a "realistic" number: the
/// point is that it can never be a plausible requirement that someone reads as real.
uint256 private constant _UNREADABLE_BOOK_LOCK = type(uint128).max;
/// @notice AUDIT FIX (R6-CF1, corrected by F3-PA-b). How many times a guardian may arm or
/// re-arm the custody freeze WITHIN ONE EPISODE before governance must intervene. Two
/// is deliberate — one initial arm plus one extension carries the freeze across the
/// full governance path with margin, and no more.
///
/// "CONSECUTIVE" IS NOW TRUE OF THE COUNTER, AND IT WAS NOT. R6-CF1 shipped this bound
/// against a LIFETIME counter that nothing ever reset except `cancelCustodyPreArm`.
/// Two arms anywhere in the protocol's life therefore spent the guardian's emergency
/// lever PERMANENTLY, and the only way back was a timelocked governance transaction —
/// i.e. the fast lever could only be restored at the speed of the slow one, which is
/// the whole thing it exists to outrun. `preArmCustodyFreeze` now opens a NEW episode
/// (count back to zero) once the previous pre-arm has lapsed AND layer-1 capital has
/// stood genuinely unfrozen for `custodyPreArmCooldown()`.
///
/// THE COOLDOWN IS WHAT KEEPS THE BOUND A BOUND. Resetting on mere lapse would let a
/// guardian chain episodes back-to-back and hold a permanent freeze with the budget
/// still nominally "spent". Because the cooldown is `MAX_CONSECUTIVE x duration`,
/// measured from the lapse, the guardian's unilateral duty cycle can never exceed 50%
/// and every episode is followed by a real, reachable, unfrozen window.
uint32 public constant CUSTODY_PRE_ARM_MAX_CONSECUTIVE = 2;
/// @dev AUDIT FIX (F3-PA-d). Gas ceiling on each governance-parameter read. A governor address
/// is governance-set and its code is not ours; an unbounded staticcall lets a hostile or
/// broken governor burn the caller's gas and take `preArmCustodyFreeze` down with it. An
/// out-of-gas sub-call returns `success == false` here, which falls back to the `Config`
/// floor — the guardian still arms.
uint256 private constant GOV_READ_GAS = 100_000;
/// @dev ERC-6372 clock description the live governance-path read requires, as the governor
/// returns it: the ABI encoding of the string, not the string's own hash. Anything else
/// denominates voting windows in units that must not be added to `block.timestamp`.
/// AUDIT FIX (F3-PA-d): comparing RETURNDATA rather than a decoded value is what removes
/// the uncatchable `abi.decode` revert — see `_clockIsTimestamp`.
string private constant CLOCK_MODE_TIMESTAMP = "mode=timestamp";
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/// @notice Initializes the module and seeds the five genesis classes with the
/// ADR-0004 default first-loss target ($10M/class).
/// @param admin Governance timelock (approves curators, sets targets).
/// @param guardian Emergency pauser (post/withdraw only — never the cascade).
/// @param upgrader Upgrade authority (timelock).
/// @param usdfr First-loss denomination asset.
/// @param registry Collateral registry (class exposure for the headroom rule).
/// @param feeVault sUSDfr vault whose conservative NAV nets this capacity.
function initialize(
address admin,
address guardian,
address upgrader,
address usdfr,
address registry,
address feeVault
) external initializer {
if (
admin == address(0) || guardian == address(0) || upgrader == address(0) || usdfr == address(0)
|| registry == address(0) || feeVault == address(0)
) revert Curator_ZeroAddress();
__AccessControl_init();
__Pausable_init();
__ReentrancyGuard_init();
__UUPSUpgradeable_init();
_grantRole(DEFAULT_ADMIN_ROLE, admin);
_grantRole(Roles.GUARDIAN_ROLE, guardian);
_grantRole(Roles.UPGRADER_ROLE, upgrader);
CuratorStorage storage $ = _storage();
$.usdfr = IERC20(usdfr);
$.registry = ICollateralRegistry(registry);
$.feeVault = IsUSDfr(feeVault);
for (uint256 classId = 1; classId <= Config.NUM_CLASSES; ++classId) {
$.targets[classId] = Config.DEFAULT_FIRST_LOSS_PER_CLASS;
emit FirstLossTargetSet(classId, Config.DEFAULT_FIRST_LOSS_PER_CLASS);
}
}
// ── Governance ───────────────────────────────────────────────────────
/// @notice Approves or revokes `curator` for `classId` (anchor curator = Forest
/// Road, additional curators pluggable per ADR-0004). Revocation blocks
/// new posts only; the existing stake keeps absorbing and stays
/// withdrawable within headroom.
function setCuratorApproved(uint256 classId, address curator, bool approved)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
if (curator == address(0)) revert Curator_ZeroAddress();
_requireKnownClass(classId);
_storage().approved[classId][curator] = approved;
emit CuratorApproved(classId, curator, approved);
}
/// @notice Sets a class's first-loss target (the subordination requirement while
/// exposure is at or above it). Governance-adjustable per ADR-0004.
function setFirstLossTarget(uint256 classId, uint256 target) external onlyRole(DEFAULT_ADMIN_ROLE) {
_requireKnownClass(classId);
_storage().targets[classId] = target;
emit FirstLossTargetSet(classId, target);
}
/// @notice Emitted when the participation-points hook changes.
event PointsModuleUpdated(address indexed module);
/// @notice Wires the participation-points hook so first-loss capital accrues points
/// (P-01). Timelocked governance only.
/// @dev P-48b: a new CODELESS module remains refused as a wiring error. The bounded observer
/// also treats legacy post-install code disappearance as a failed notification, so it
/// cannot turn this optional ledger into a financial liveness dependency.
/// @param module The points ledger, or zero to disable the hook entirely.
function setPointsModule(address module) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (module != address(0) && module.code.length == 0) revert Curator_PointsModuleNotAContract(module);
_storage().pointsModule = IPointsModule(module);
emit PointsModuleUpdated(module);
}
/// @notice The wired participation-points hook (zero disables it).
function pointsModule() external view returns (address) {
return address(_storage().pointsModule);
}
// ── Curator paths ────────────────────────────────────────────────────
/// @inheritdoc ICuratorModule
function postFirstLoss(uint256 classId, uint256 amount) external nonReentrant whenNotPaused {
CuratorStorage storage $ = _storage();
if (!$.approved[classId][msg.sender]) revert Curator_NotApprovedCurator(classId, msg.sender);
if (amount == 0) revert Curator_ZeroAmount();
$.feeVault.beginFeeNeutralMarkedNavChange();
ClassPool storage pool = $.pools[classId];
// A wiped pool (balance zero, shares outstanding) starts a new round: the old
// shares are worthless and must not dilute fresh capital.
//
// ── AUDIT FIX (SWEEP-3 S3-F1) — "WIPED" IS A RATIO, NOT AN EXACT ZERO ────────────────
//
// LOAD-BEARING. DO NOT NARROW THIS BACK TO `pool.balance == 0`, AND DO NOT DELETE THE
// `pool.totalShares = pool.balance` LINE BELOW.
//
// WHAT WAS WRONG. The predicate was `pool.balance == 0 && pool.totalShares != 0`, an EXACT
// wipe. `absorbLoss`/`absorbGlobalLoss` clamp to what the pool holds, so a loss ONE WEI
// short of the balance left the round standing with a collapsed share price, and every
// later `postFirstLoss` multiplied the share/balance ratio by `total / residual`.
// The residual is ATTACKER-CHOSEN: `MintRedeemController._exitDrawTarget` is
// `ceil(usdfrIn * deficit / backing)` and the redeemer picks `usdfrIn` at 1-wei
// granularity, so the draw takes EVERY integer value in range including `curatorTotal - 1`.
// Any KYC'd USDfr holder, any time the book is short, no role required.
//
// MEASURED: ONE permissionless under-backed redemption left ALL FIVE class pools at 1 wei
// against 1,000e18 shares (ratio 1e21). Three such draws with ordinary recapitalisation in
// between made `postFirstLoss` revert on `Math.mulDiv` overflow for EVERY curator, while
// `postedOf` floored to zero for every holder of less than the whole share supply — so
// nobody could withdraw the surviving wei that kept the round from advancing. Cascade
// layer 1 was unfundable for that class, with no governance lever on `pools[classId]`.
// This is a LIVENESS defect, not a value-conservation one: attribution stayed exact
// throughout (`test_S3_N1_theInflatedRatioStillAttributesValueCorrectly`).
//
// WHY 1e18. At `balance * 1e18 <= totalShares` the share price is at or below 1e-18, i.e.
// one share is worth less than the smallest representable unit of an 18-decimal token: the
// old stakes are economically nil. THE MAXIMUM ANYONE LOSES AT AN ADVANCE IS THE WHOLE
// RESIDUAL `balance`, and the rule is self-limiting — because the ratio can never exceed
// 1e18, `balance >= totalShares / 1e18`, and `totalShares` is bounded by what was posted
// in the round. On a 1,000,000e18 pool that caps the forfeited dust at 1e6 wei
// (1e-12 USDfr). It also bounds `mulDiv(amount, totalShares, balance) <= amount * 1e18`,
// which is what removes the overflow brick.
//
// WHY `totalShares = pool.balance` AND NOT ZERO. Zeroing the shares while a non-zero
// residual stands would mint `shares == amount` against `balance == amount + residual`,
// pushing the share price ABOVE 1 and breaking the shipped invariant this contract's own
// NatSpec relies on (measured: `[FAIL: share price never exceeds 1]`). Seeding the new
// round with `totalShares == balance` leaves the price at exactly 1 — the new round opens
// 1:1 — and the residual stands as backing that keeps absorbing before any curator's fresh
// capital.
//
// ── AUDIT FIX (SWEEP-4 S4-R1) — THE RESIDUAL IS NOW OWNED, NOT FORFEITED ─────────────
//
// WHAT S3-F1 GOT WRONG. It called the forfeited residual "dust" and bounded it by
// `totalShares / 1e18`, reasoning from a share price near 1. THE BOUND DOES NOT HOLD:
// `totalShares` is not bounded by the balance. A post made while the price is already
// collapsed mints `mulDiv(amount, totalShares, balance)`, which inflates `totalShares` by
// up to 1e18x against the SAME balance — so after one ordinary recapitalisation the close
// threshold sits just under the WHOLE pool. MEASURED (`SweepR4_CuratorClosedRounds`):
// a 999000999000999002-wei loss (0.0999% of the pool) closed the round and destroyed a
// 1000000000000000001001-wei curator claim. A thousandfold amplification of the loss the
// cascade actually took, reachable by any KYC'd redeemer on the ADR-0034 Y-bis draw path.
//
// THE FIX IS A SNAPSHOT, NOT A RESERVE. `_advanceRoundIfWiped` records
// `closedRounds[classId][round] = {shares: oldTotalShares, carriedShares: balance}`: the
// closing cohort collectively owns the `balance` shares the new round opens with, and
// `_settleStaleRound` hands each of them their pro-rata slice lazily.
//
// WHY NOT A SEPARATE CLAIM RESERVE — REJECTED, WITH THE REASON. Moving the residual OUT of
// `pool.balance` into a set-aside pot is the obvious shape, and it INVERTS THE CASCADE:
// that residual is curator capital, it is layer 1, and CLAUDE.md §1.3 requires it to absorb
// before the sGROVE backstop and before depositor principal. A set-aside stops absorbing,
// so the next loss of that size would skip layer 1 and land on layer 2 — and because the
// residual is NOT bounded as dust (see above), the amount skipped is not bounded either.
// A set-aside would also drop `poolBalance()`, which is the exact quantity
// `ConservativeImpairmentMath.pendingSeniorImpairment` reads as layer-1 credit, so the two
// enumerations would disagree — the SEAM-class defect this repository has paid for twice.
// The snapshot form moves NOTHING: `pool.balance`, `poolBalance()`, `headroom()`,
// `absorbLoss` and `absorbGlobalLoss` are all bit-for-bit unchanged by a close, and the
// carried shares dilute with every later loss exactly as the capital behind them does.
//
// Falsified by `test_S3_F1_layerOneMustStillBeReFundableAfterNearTotalExitDraws`,
// `test_S3_F1_theFacilityRouteInflatesTheShareRatioIdentically` and
// `test_S3_F1_oneExitDrawCanCollapseTheShareRatioInEveryClassAtOnce`. The control
// `test_S3_F1_control_aFullDrawAdvancesTheRoundAndRecapitalisationKeepsWorking` pins that
// the exact-wipe behaviour is unchanged.
//
// WHY THE NORMALISATION IS LAZY — IT BELONGS HERE AND NOWHERE ELSE. I first put the same
// call in `absorbLoss`/`absorbGlobalLoss` so a collapsed ratio could never even STAND in
// storage. MEASURED, that broke a real value property: `testFuzz_absorbLoss_proRataExact`
// reds with `at most 1 wei dust per curator: 2 < 4`, because advancing the round inside the
// absorption zeroes stale stakes and a curator's legitimate claim on the 4-wei residual is
// forfeited AT THE LOSS. Attribution is exact while the ratio merely SITS collapsed —
// `postedOf` still floors correctly and `withdrawFirstLoss` still works — so the collapse
// is only ever harmful at the next MINT, which is exactly here. Normalising at the loss
// traded a real attribution property for a cosmetic one. DO NOT MOVE THIS CALL INTO THE
// CASCADE. (Consequence, stated rather than hidden: between a near-total absorption and the
// next post, `poolShares()` publishes a ratio a reader cannot interpret. It is inert —
// nothing in `src/` consumes it — and it is registered as INFO.)
_advanceRoundIfWiped($, classId, pool);
_normalizePoolShares(classId, pool);
CuratorStake storage stake = $.stakes[classId][msg.sender];
// AUDIT FIX (SWEEP-4 S4-R1) — THIS REPLACED `stake.shares = 0`, AND MUST NOT GO BACK.
// Unconditionally zeroing a stale stake is what forfeited the residual. Settling converts
// it instead; a stake too stale to convert in one step REFUSES the post rather than
// erasing the claim (see `_settleStaleRound` for why the refusal is not a brick).
// `stakeRound` is read BEFORE settling: the whole call reverts, so reporting the post-hop
// round would tell an operator where the stake is NOT.
uint256 stakeRound = stake.round;
if (!_settleStaleRound($, classId, pool, msg.sender, stake)) {
revert Curator_UnsettledClosedRound(classId, stakeRound, pool.round);
}
_syncStakeShares(pool, stake);
// SHARE-PRICE <= 1 INVARIANT (fuzzed in CreditInvariants): only absorption
// changes the balance/share ratio, and only downward; withdrawals burn
// ceil-rounded shares, which cannot push the price above 1. Therefore
// totalShares >= balance always, and shares >= amount >= 1 here — no zero-share
// mint is reachable.
uint256 shares;
if (pool.totalShares == 0) {
shares = amount;
} else {
uint256 availableShares = type(uint256).max - pool.totalShares;
if (amount > availableShares / 2) revert Curator_ShareCapacityExceeded(amount, availableShares);
shares = Math.mulDiv(amount, pool.totalShares, pool.balance);
}
stake.shares += shares;
stake.shareScale = pool.shareScale;
pool.totalShares += shares;
pool.balance += amount;
$.usdfr.safeTransferFrom(msg.sender, address(this), amount);
$.feeVault.endFeeNeutralMarkedNavChange();
emit FirstLossPosted(classId, msg.sender, amount, shares, pool.round);
_notifyPoints($, classId, msg.sender); // P-01: accrue points on the new posted first-loss
}
/// @inheritdoc ICuratorModule
/// @dev ADR-0034 Y-bis NOTE (SWEEP-1 CSG-N1, 2026-08-08) — STATED BECAUSE IT IS CURRENTLY
/// INCIDENTAL, NOT DESIGNED. `DefaultManager.drawForSeniorExit` charges ALL FIVE class
/// pools pro-rata, but R4-EC2's `unresolvedDefaults` freeze is PER CLASS, so a curator in
/// an untouched class looks free to run ahead of a draw that will charge them.
///
/// IT IS CLOSED, EXACTLY, BY R6-CF1 LIMB 4 — but only by coincidence of predicate.
/// `MintRedeemController._exitDrawTarget` returns non-zero only while
/// `usdfr.totalSupply() > reserves.totalBackingValue()`, and `custodyLossUnabsorbed()`
/// limb 4 reads `controller.totalUSDfr() > controller.backingValue()`, which are literally
/// the same two reads. So the freeze is live on precisely the set where a draw can fire,
/// and it freezes EVERY class, not just the defaulted one — verified end to end
/// (a FILM-only impairment leaves `unresolvedDefaults(ENERGY) == 0` and an ENERGY
/// withdrawal still reverts `Curator_CustodyLossFrozen`).
///
/// THE WARNING: nothing pins that coincidence. A future change to `_exitDrawTarget`'s
/// predicate — widening it beyond the under-backed set, for instance — would silently
/// re-open a curator escape ahead of a crystallisation that ADR-0034 Y-bis's own
/// implementation requirements say must not be escapable. If you touch
/// `_exitDrawTarget`'s guard, re-derive this coupling.
function withdrawFirstLoss(uint256 classId, uint256 amount) external nonReentrant whenNotPaused {
CuratorStorage storage $ = _storage();
if (amount == 0) revert Curator_ZeroAmount();
// AUDIT FIX (R4-EC2): once a facility in this class has defaulted, the curator
// cannot withdraw until governance resolves the workout — otherwise a curator
// could front-run realizeLoss and pull excess first-loss ahead of the loss.
if ($.unresolvedDefaults[classId] != 0) revert Curator_ClassDefaultFrozen(classId);
// AUDIT FIX (R6-CF1) — LOAD-BEARING, DO NOT DELETE. The R4-EC2 guard above covers only the
// FACILITY path: `unresolvedDefaults` has exactly one writer, `freezeOnDefault`, reached
// from `declareDefault`/`liquidate`. The live reserve-CUSTODY path is
// `ReserveManager.ratifyAndOpen -> _absorbRecognizedReserveLoss ->
// _drawJuniorReserveLoss -> absorbGlobalLoss`; before this guard it armed NOTHING, so a
// curator could pull every dollar of headroom between the incident being recognised and
// the write-down executing, and duck a loss this capital is CASCADE LAYER 1 for. That is
// the same inversion R4-EC2's own comment describes, on the other loss path.
//
// The predicate is class-INDEPENDENT because a custody loss has no collateral class:
// `absorbGlobalLoss` charges all five pools pro-rata, so every pool is at risk.
// See `IReserveManager.custodyLossUnabsorbed` for the five limbs and the window each
// covers. Fail CLOSED when unwired: "cannot tell" must not read as "clear" here.
if (address($.reserveManager) == address(0)) revert Curator_ReserveNotWired();
if (custodyFreezeActive()) revert Curator_CustodyLossFrozen();
ClassPool storage pool = $.pools[classId];
CuratorStake storage stake = $.stakes[classId][msg.sender];
// AUDIT FIX (SWEEP-4 S4-R1) — LOAD-BEARING. Without this a closed-round residual is
// claimable in principle and unreachable in practice: `_postedOf` floors a stale stake to
// zero, so every withdrawal of it would revert `Curator_InsufficientStake` and the claim
// the snapshot preserved could never become USDfr. It sits AFTER both freezes deliberately
// — a frozen class must not settle-and-exit in one call — and settling is always available
// on its own through the permissionless `claimClosedRound`.
uint256 stakeRound = stake.round; // read BEFORE settling — see `postFirstLoss`
if (!_settleStaleRound($, classId, pool, msg.sender, stake)) {
revert Curator_UnsettledClosedRound(classId, stakeRound, pool.round);
}
_syncStakeShares(pool, stake);
uint256 posted = _postedOf(pool, stake);
if (amount > posted) revert Curator_InsufficientStake(classId, msg.sender, amount, posted);
uint256 free = _headroom($, classId, pool);
if (amount > free) revert Curator_HeadroomExceeded(classId, amount, free);
$.feeVault.beginFeeNeutralMarkedNavChange();
// Shares burn rounds UP so a withdrawal can never take more value than the
// caller's stake is worth (rounding dust favors the pool, i.e. the senior
// side). Because amount <= posted = floor(shares·balance/totalShares), the
// ceil here never exceeds the caller's shares (ceil(x) <= n iff x <= n).
uint256 shares = Math.mulDiv(amount, pool.totalShares, pool.balance, Math.Rounding.Ceil);
stake.shares -= shares;
pool.totalShares -= shares;
pool.balance -= amount;
$.usdfr.safeTransfer(msg.sender, amount);
$.feeVault.endFeeNeutralMarkedNavChange();
emit FirstLossWithdrawn(classId, msg.sender, amount, shares, pool.round);
_notifyPoints($, classId, msg.sender); // P-01: reconcile points to the reduced posted first-loss
}
/// @inheritdoc ICuratorModule
/// @dev AUDIT FIX (SWEEP-4 S4-R1) — LOAD-BEARING, DO NOT DELETE. This is the ESCAPE that makes
/// the `Curator_UnsettledClosedRound` refusal in `postFirstLoss`/`withdrawFirstLoss` a
/// two-transaction path rather than a brick: those two must revert on a stake that cannot
/// be brought to the live round in one conversion (silently erasing it is the defect), and
/// this walks the stake forward one closed round per call with no revert at all.
///
/// PERMISSIONLESS, AND THAT IS DELIBERATE. It moves no value and grants the caller
/// nothing: it only re-attributes shares that were minted at the close and have been part
/// of `poolShares(classId)` ever since. Making it caller-restricted would put layer-1
/// recapitalisation liveness — the very property S3-F1 exists to protect — behind one
/// address being available and willing to transact.
///
/// NOT PAUSABLE AND NOT FREEZE-GATED, ALSO DELIBERATE. Both withdrawal freezes (R4-EC2
/// `unresolvedDefaults`, R6-CF1 `custodyFreezeActive`) and the guardian pause exist to stop
/// capital LEAVING ahead of a loss. Settling leaves nothing: the settled shares sit in the
/// same pool, absorb the same losses, and can only be withdrawn through
/// `withdrawFirstLoss`, where every one of those guards still binds. Gating attribution on
/// them would instead mean a curator's residual claim decays while the class is frozen,
/// which inverts what the freezes are for.
function claimClosedRound(uint256 classId, address curator) external nonReentrant {
_requireKnownClass(classId);
if (curator == address(0)) revert Curator_ZeroAddress();
CuratorStorage storage $ = _storage();
ClassPool storage pool = $.pools[classId];
// CORR-DELTA-05: notify points only once the stake reaches the active round; an
// intermediate 32-hop chunk would otherwise report `_postedOf == 0` and reset maturity.
if (_settleStaleRound($, classId, pool, curator, $.stakes[classId][curator])) {
_notifyPoints($, classId, curator);
}
}
// ── Cascade layer 1 (credit layer only; never pausable) ──────────────
/// @inheritdoc ICuratorModule
function absorbLoss(uint256 classId, uint256 loss)
external
onlyRole(Roles.CREDIT_ROLE)
nonReentrant
returns (uint256 absorbed, uint256 residual)
{
if (loss == 0) revert Curator_ZeroAmount();
CuratorStorage storage $ = _storage();
ClassPool storage pool = $.pools[classId];
uint256 balanceBefore = pool.balance;
absorbed = loss < pool.balance ? loss : pool.balance;
residual = loss - absorbed;
if (absorbed != 0) {
// Shares are untouched: every staker in the class dilutes pro-rata.
pool.balance -= absorbed;
// NOTE (SWEEP-3 S3-F1): the round is deliberately NOT advanced here. See the
// "WHY THE NORMALISATION IS LAZY" paragraph in `postFirstLoss`.
$.usdfr.safeTransfer(msg.sender, absorbed);
}
emit LossAbsorbed(classId, loss, absorbed, residual);
// AUDIT FIX (P-01 follow-up / H-03): a loss dilutes every curator's postedOf without a
// per-curator hook, so freeze curator point accrual in this class at the loss instant
// until each curator reconciles. The bracketing pool balances are passed through so the
// ledger can write each curator's stale cached balance down by the EXACT pro-rata
// dilution (shares are untouched here, only `pool.balance` moves) — otherwise a curator
// who tops back up to their pre-loss notional keeps the destroyed capital's maturity
// ramp. FAIL-OPEN — never block the never-pausable cascade.
if (absorbed != 0) {
IPointsModule pm = $.pointsModule;
if (address(pm) != address(0)) {
_callLossPoints(
pm, abi.encodeCall(pm.onCuratorLoss, (classId, balanceBefore, pool.balance)), classId, 0
);
}
}
}
/// @inheritdoc ICuratorModule
function absorbGlobalLoss(uint256 loss)
external
onlyRole(Roles.CREDIT_ROLE)
nonReentrant
returns (uint256 absorbed, uint256 residual)
{
if (loss == 0) revert Curator_ZeroAmount();
CuratorStorage storage $ = _storage();
uint256[5] memory balances;
uint256[5] memory allocations;
uint256 total;
IPointsModule pm = $.pointsModule;
for (uint256 i = 0; i < Config.NUM_CLASSES; ++i) {
balances[i] = $.pools[i + 1].balance;
total += balances[i];
}
absorbed = loss < total ? loss : total;
residual = loss - absorbed;
if (absorbed == 0) return (0, residual);
uint256 allocated;
for (uint256 i = 0; i < Config.NUM_CLASSES; ++i) {
allocations[i] = Math.mulDiv(absorbed, balances[i], total);
allocated += allocations[i];
}
uint256 dust = absorbed - allocated;
for (uint256 i = 0; i < Config.NUM_CLASSES && dust != 0; ++i) {
uint256 remainingCapacity = balances[i] - allocations[i];
if (remainingCapacity == 0) continue;
uint256 add = dust < remainingCapacity ? dust : remainingCapacity;
allocations[i] += add;
dust -= add;
}
assert(dust == 0);
for (uint256 i = 0; i < Config.NUM_CLASSES; ++i) {
uint256 amount = allocations[i];
if (amount == 0) continue;
uint256 classId = i + 1;
ClassPool storage pool = $.pools[classId];
pool.balance -= amount;
// NOTE (SWEEP-3 S3-F1): the ADR-0034 Y-bis senior-exit draw arrives HERE, and it is the
// path whose residual an unprivileged redeemer picks to the wei — but the round is
// deliberately NOT advanced here. See "WHY THE NORMALISATION IS LAZY" in
// `postFirstLoss`.
emit LossAbsorbed(classId, amount, amount, 0);
}
// Complete the mandatory financial leg before any optional callback can exhaust gas.
// Every callback observes the coherent final allocation and its exact before/after ratio.
$.usdfr.safeTransfer(msg.sender, absorbed);
if (address(pm) != address(0)) {
for (uint256 i = 0; i < Config.NUM_CLASSES; ++i) {
uint256 amount = allocations[i];
if (amount == 0) continue;
_callLossPoints(
pm,
abi.encodeCall(pm.onCuratorLoss, (i + 1, balances[i], balances[i] - amount)),
i + 1,
(Config.NUM_CLASSES - i - 1) * POINTS_HOOK_ITERATION_GAS
);
}
}
}
// ── Default freeze (audit R4-EC2) ────────────────────────────────────
/// @inheritdoc ICuratorModule
/// @dev This CREDIT_ROLE hook is not gated by the curator pause. DefaultManager
/// may first need legacy PIK posting, whose dependencies can be paused.
/// Each recorded default increments a counter and requires its own lift.
function freezeOnDefault(uint256 classId) external onlyRole(Roles.CREDIT_ROLE) {
_requireKnownClass(classId);
CuratorStorage storage $ = _storage();
uint256 count = $.unresolvedDefaults[classId] + 1;
$.unresolvedDefaults[classId] = count;
emit ClassDefaultFrozen(classId, count);
}
/// @inheritdoc ICuratorModule
/// @dev Governance timelock lifts one freeze once a workout resolves. Reverts if the
/// class is not frozen, so lifts can never drive the counter below zero.
function liftDefaultFreeze(uint256 classId) external onlyRole(DEFAULT_ADMIN_ROLE) {
_requireKnownClass(classId);
CuratorStorage storage $ = _storage();
uint256 count = $.unresolvedDefaults[classId];
if (count == 0) revert Curator_NotFrozen(classId);
count -= 1;
$.unresolvedDefaults[classId] = count;
emit ClassDefaultFreezeLifted(classId, count);
}
// ── Custody-loss freeze (audit R6-CF1) ───────────────────────────────
/// @inheritdoc ICuratorModule
/// @dev AUDIT FIX (R6-CF1) — LOAD-BEARING, DO NOT DELETE. `withdrawFirstLoss` refuses while
/// this is true. The predicate is DERIVED from reserve state rather than latched into a
/// counter, and that is the point of the fix: the finding was that the facility path
/// armed a counter and no custody path armed anything, so a NEW custody entry point could
/// re-open the hole simply by forgetting to call an arming function. A derived predicate
/// cannot be forgotten.
///
/// TWO LIMBS. The guardian PRE-ARM covers a loss that is known but not yet visible
/// on-chain and that governance has not had time to recognise. Everything else is
/// `IReserveManager.custodyLossUnabsorbed`, which is the C-01 release condition verbatim:
/// release only when absorption is complete, no deficit or live shortfall remains, and
/// `totalUSDfr() <= backingValue()`.
///
/// NOTE THE ASYMMETRY, IT IS DELIBERATE: a guardian can turn this ON and has NO way to
/// turn it off, and governance's `cancelCustodyPreArm` clears only the pre-arm limb.
/// Neither role can release a genuine custody freeze early.
///
/// DELETION COVERAGE (audit F3-FREEZE-01). Both branches below are LOAD-BEARING and both
/// are mutation-covered — deleting either must turn a test red, which is the only thing
/// that stops a guard degrading into decoration:
/// pre-arm branch -> Fix_R6CF1-freeze-limb-isolation.t.sol::..._preArmIsTheOnlyLimb
/// (drives the pre-arm while EVERY reserve limb is provably off, so
/// the reserve predicate cannot mask its deletion), and the stateful
/// `INV_CustodyFreezePredicate` guards `preArm:*`.
/// unwired branch -> ..._unwiredReserveReadsAsFrozen, and the stateful `unwired:*` guards.
/// The positive control lives beside them (`..._clearStateIsNotAPermanentFreeze` and the
/// `clear` guard): a mutant that simply returns `true` must fail too, otherwise "always
/// frozen" would pass every negative test in the file.
function custodyFreezeActive() public view returns (bool) {
CuratorStorage storage $ = _storage();
if ($.custodyPreArmExpiry > block.timestamp) return true;
IReserveManager reserves_ = $.reserveManager;
// Unwired reads as FROZEN. A guard that silently disappears when its input is missing is
// not a guard (CLAUDE.md prime directive 4); post-deploy validation catches the wiring.
if (address(reserves_) == address(0)) return true;
return reserves_.custodyLossUnabsorbed();
}
/// @inheritdoc ICuratorModule
/// @dev AUDIT FIX (R6-CF1). NOT pausable and NOT bounded by a class: a guardian must always be
/// able to stop layer-1 capital leaving, and a custody loss charges every pool.
/// Re-arming REPLACES the standing pre-arm with `block.timestamp + duration` and consumes
/// budget; see `CUSTODY_PRE_ARM_MAX_CONSECUTIVE` for why the budget is what stops a
/// guardian from freezing curator capital indefinitely.
///
/// CORRECTED (SWEEP-1 CSG-F3, 2026-08-08) — THIS LINE SAID RE-ARMING "EXTENDS" THE
/// STANDING PRE-ARM. IT DOES NOT, AND MUST NOT. `duration` is derived LIVE from the
/// governance path (`_derivePreArm`), so whenever that path has SHORTENED since the last
/// arm — including the one-transaction case `setGovernor(address(0))`, which collapses
/// the 90-day window to the 15-day `Config` floor — a good-faith re-arm SHORTENS the
/// window AND spends a unit of budget doing it. MEASURED: a 90-day arm followed by a
/// governance retune and a re-arm dropped the expiry by 74 days, exhausting the budget,
/// after which the ENTIRE 300,000e18 layer-1 pool was withdrawable inside the window the
/// first arm had already covered.
///
/// DO NOT "FIX" THIS WITH `expiry = max(previousExpiry, now + duration)`. MEASURED: that
/// reds three `CustodyPreArmInvariants` assertions —
/// "pre-arm EXPIRY diverged from the independent model", "custodyFreezeActive() != the
/// independent model of the guardian pre-arm limb", and "layer 1 refused while nothing was
/// armed - the pre-arm has become a lock". `expiry = now + duration` is DELIBERATE: a
/// `max()` breaks the <=50% guardian duty-cycle bound that F3-PA-b exists to enforce, and
/// turns the emergency lever into a permanent freeze. THE TWO PROPERTIES GENUINELY
/// CONFLICT and the conflict was written down nowhere; this paragraph is where it is
/// written down. OPERATOR RULE: read `custodyPreArmDuration()` BEFORE re-arming — if it
/// has fallen below the remaining life of the standing pre-arm, re-arming makes the
/// protection worse, not better.
///
/// AUDIT FIX (F3-PA-b) — THE CONSECUTIVE-EPISODE RESET IS LOAD-BEARING, DO NOT DELETE.
/// Without it `custodyPreArmCount` is a LIFETIME counter and the guardian's emergency
/// lever is permanently spent after two arms in the protocol's entire life, restorable
/// only by a timelocked governance transaction. WITHOUT THE `+ cooldown` TERM the reset
/// is equally wrong in the other direction: a guardian could re-arm the instant the
/// previous window lapsed and hold a permanent freeze on layer-1 capital while the budget
/// still read as spent. Both halves of the predicate are guards; both are mutation-tested
/// (`Fix_F3PA-prearm-budget-trap.t.sol`) and driven statefully by
/// `test/invariant/CustodyPreArmInvariants.t.sol`.
///
/// AUDIT FIX (F3-PA-c) — the truncation signal at the end is a guard too. The cap on the
/// derivation path is allowed to bind, but it is NEVER allowed to bind silently: an
/// operator watching this event learns that one window no longer outlasts the live
/// governance path and that `replenishCustodyPreArmBudget` must carry the difference.
function preArmCustodyFreeze() external onlyRole(Roles.GUARDIAN_ROLE) {
CuratorStorage storage $ = _storage();
(uint256 livePath, uint64 duration) = _derivePreArm();
uint64 previousExpiry = $.custodyPreArmExpiry;
uint32 count = $.custodyPreArmCount;
// GUARD (F3-PA-b): a NEW episode begins once the previous pre-arm has lapsed AND layer-1
// has stood genuinely unfrozen for the full cooldown. `previousExpiry` is the lapse
// instant; the cooldown is measured from it, so the unfrozen window is real elapsed time
// and not an artefact of when the guardian happens to call.
uint256 cooldown = uint256(duration) * CUSTODY_PRE_ARM_MAX_CONSECUTIVE;
if (count != 0 && block.timestamp >= uint256(previousExpiry) + cooldown) {
emit CustodyFreezePreArmEpisodeReset(count, previousExpiry);
count = 0;
}
count += 1;
if (count > CUSTODY_PRE_ARM_MAX_CONSECUTIVE) {
revert Curator_PreArmBudgetExhausted(count, CUSTODY_PRE_ARM_MAX_CONSECUTIVE);
}
uint64 expiry = uint64(block.timestamp) + duration;
$.custodyPreArmCount = count;
$.custodyPreArmExpiry = expiry;
emit CustodyFreezePreArmed(msg.sender, expiry, count);
// GUARD (F3-PA-c): the cap may bind, but never silently.
if (uint256(duration) <= livePath) {
emit CustodyFreezePreArmTruncated(livePath, duration, count);
}
}
/// @inheritdoc ICuratorModule
/// @dev AUDIT FIX (R6-CF1). Governance's answer to a FALSE ALARM. It clears BOTH the standing
/// pre-arm and the budget, because a false alarm means no protection is wanted. It is safe
/// to give governance this because it clears only the pre-arm limb — an open incident, a
/// latched deficit, a live shortfall or an under-backed protocol all keep
/// `custodyFreezeActive()` true regardless. DO NOT extend this to clear the derived limbs:
/// that would hand governance a loss-dodging lever and undo the fix.
///
/// AUDIT FIX (F3-PA-a) — THIS IS NO LONGER THE BUDGET-REPLENISHMENT LEVER, and it must
/// never become one again. R6-CF1 shipped it as the ONLY way to replenish the guardian's
/// budget while it also zeroes `custodyPreArmExpiry`. Using it for its documented purpose
/// — "governance has looked, the incident is REAL, keep going" — therefore destroyed the
/// very protection it was called to extend, and in the same block a curator could take
/// every dollar of layer-1 headroom out ahead of a loss it is layer 1 for. That is the
/// HIGH. `replenishCustodyPreArmBudget` is the lever for a REAL incident; this one is for
/// a false alarm and nothing else.
function cancelCustodyPreArm() external onlyRole(DEFAULT_ADMIN_ROLE) {
CuratorStorage storage $ = _storage();
uint64 previous = $.custodyPreArmExpiry;
if (previous == 0 && $.custodyPreArmCount == 0) revert Curator_NoPreArm();
$.custodyPreArmExpiry = 0;
$.custodyPreArmCount = 0;
emit CustodyFreezePreArmCancelled(previous);
}
/// @inheritdoc ICuratorModule
/// @dev AUDIT FIX (F3-PA-a) — LOAD-BEARING, DO NOT DELETE, AND DO NOT "SIMPLIFY" IT INTO
/// `cancelCustodyPreArm`. The one line that matters is the line that ISN'T here: this
/// function must NOT write `custodyPreArmExpiry`. Replenishing the guardian's budget is
/// what governance does when it has looked at the incident and found it REAL; if that act
/// also cleared the standing pre-arm it would open, at minimum, a one-transaction window
/// in which layer-1 capital is free to leave ahead of the loss — and a curator can be the
/// very next transaction. Adding a mutation here that zeroes the expiry reds
/// `test_F3PA_replenishingBudgetMustNotDestroyActiveProtection` and the stateful
/// `invariant_PA2_freezeMatchesIndependentModel`.
function replenishCustodyPreArmBudget() external onlyRole(DEFAULT_ADMIN_ROLE) {
CuratorStorage storage $ = _storage();
uint32 spent = $.custodyPreArmCount;
if (spent == 0) revert Curator_NoPreArm();
$.custodyPreArmCount = 0;
emit CustodyFreezePreArmBudgetReplenished(spent, $.custodyPreArmExpiry);
}
/// @inheritdoc ICuratorModule
function custodyPreArm() external view returns (uint64 expiry, uint32 count) {
CuratorStorage storage $ = _storage();
return ($.custodyPreArmExpiry, $.custodyPreArmCount);
}
/// @inheritdoc ICuratorModule
/// @dev AUDIT FIX (R6-CF1) — DO NOT REPLACE WITH A LITERAL. A pre-arm that expires before
/// governance could possibly have ratified it is decoration: the guardian arms, the
/// freeze lapses mid-proposal, and the curator exits anyway. The requirement is therefore
/// that this strictly EXCEED the governance path it was derived from,
/// `custodyPreArmGovernancePath()`.
///
/// All three terms are governance-mutable, so the live reading (when a governor is wired)
/// is taken and used whenever it is longer than the `Config` launch floor. The +50% is the
/// margin over the protocol-enforced minimum: proposal drafting, queueing and execution
/// latency all sit on top of it.
///
/// AUDIT FIX (F3-PA-c). The cap now binds on the PATH (`CUSTODY_PRE_ARM_MAX_PATH`), and
/// `CUSTODY_PRE_ARM_MAX_DURATION` is exactly 3/2 of it, so the clamp on the last line is
/// provably non-binding and `custodyPreArmDuration() > custodyPreArmGovernancePath()`
/// holds at EVERY parameterisation — it is fuzzed as such. R6-CF1 capped the DURATION
/// while summing three separately-capped terms, so a live path of up to 3 x 90 days was
/// truncated to a 90-day window and the requirement above silently inverted. Where the
/// path cap genuinely binds (a live path beyond `CUSTODY_PRE_ARM_MAX_PATH`) the shortfall
/// is reported by `custodyPreArmCoversLiveGovernancePath`, emitted by
/// `CustodyFreezePreArmTruncated`, and — from P-49 — actually checked at deploy time by
/// `script/Validate.s.sol`, which requires `custodyPreArmCoversLiveGovernancePath()`.
/// That refuses the regime where the derived duration no longer outlasts the live path
/// (a live path at or above `CUSTODY_PRE_ARM_MAX_DURATION`), NOT merely where the path
/// cap binds. Before P-49 the validator asserted `custodyPreArmDuration()` against the
/// `Config` launch path — an assertion `_governancePath()`'s own floor makes
/// UNFALSIFIABLE, since the floor guarantees a duration of at least 15 days against a
/// 10-day bound.
function custodyPreArmDuration() public view returns (uint64 duration) {
(, duration) = _derivePreArm();
}
/// @inheritdoc ICuratorModule
/// @dev AUDIT FIX (F3-PA-c). The path the duration is actually derived from: the longer of the
/// `Config` launch floor and the live reading, bounded by `CUSTODY_PRE_ARM_MAX_PATH`.
function custodyPreArmGovernancePath() public view returns (uint64) {
uint256 path = _governancePath();
return path > CUSTODY_PRE_ARM_MAX_PATH ? CUSTODY_PRE_ARM_MAX_PATH : uint64(path);
}
/// @inheritdoc ICuratorModule
/// @dev AUDIT FIX (F3-PA-c) — a REAL consumer, not a decorative view. `script/Validate.s.sol`
/// refuses to validate a deployment where this is false, and `preArmCustodyFreeze` emits
/// `CustodyFreezePreArmTruncated` whenever it arms into that regime.
function custodyPreArmCoversLiveGovernancePath() public view returns (bool) {
(uint256 livePath, uint64 duration) = _derivePreArm();
return uint256(duration) > livePath;
}
/// @inheritdoc ICuratorModule
/// @dev AUDIT FIX (F3-PA-b). `MAX_CONSECUTIVE x duration`, measured from the lapse of the
/// previous pre-arm, so a guardian's unilateral duty cycle over layer-1 capital can never
/// exceed one half.
function custodyPreArmCooldown() public view returns (uint64) {
(, uint64 duration) = _derivePreArm();
return uint64(uint256(duration) * CUSTODY_PRE_ARM_MAX_CONSECUTIVE);
}
/// @inheritdoc ICuratorModule
/// @dev AUDIT FIX (R6-CF1). Zero is accepted and means "explicitly unwired", which reads as
/// FROZEN — there is no configuration of this module in which the custody guard is
/// silently absent. A non-zero address must answer `usdc()`, which both requires code and
/// rejects an address that is not a ReserveManager.
function setReserveManager(address reserves_) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (address(_storage().reserveManager) != address(0) && custodyFreezeActive()) {
revert Curator_ReserveManagerChangeFrozen();
}
if (reserves_ != address(0)) {
if (reserves_.code.length == 0) revert Curator_InvalidReserveManager(reserves_);
try IReserveManager(reserves_).usdc() returns (address token) {
if (token == address(0)) revert Curator_InvalidReserveManager(reserves_);
} catch {
revert Curator_InvalidReserveManager(reserves_);
}
}
_storage().reserveManager = IReserveManager(reserves_);
emit ReserveManagerUpdated(reserves_);
}
/// @inheritdoc ICuratorModule
/// @dev AUDIT FIX (R6-CF1). Zero leaves the `Config` launch parameters as the sole source of
/// the pre-arm duration — safe, because those are a FLOOR the live reading can only raise.
function setGovernor(address governor_) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (governor_ != address(0) && governor_.code.length == 0) revert Curator_InvalidGovernor(governor_);
_storage().governor = governor_;
emit GovernorUpdated(governor_);
}
/// @notice Governance recovery route if a Guardian pause halted curator user paths.
function governanceUnpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
_unpause();
}
/// @notice The wired ReserveManager whose custody-loss window gates withdrawals (0 = frozen).
function reserveManager() external view returns (address) {
return address(_storage().reserveManager);
}
/// @notice The wired governor the pre-arm duration is derived from (0 = `Config` floor only).
function governor() external view returns (address) {
return _storage().governor;
}
// ── Guardian ─────────────────────────────────────────────────────────
/// @notice Pauses curator post/withdraw. The cascade (`absorbLoss`) is NEVER
/// pausable — see the contract-level note.
function pause() external onlyRole(Roles.GUARDIAN_ROLE) {
_pause();
}
/// @notice Unpauses curator post/withdraw.
function unpause() external onlyRole(Roles.GUARDIAN_ROLE) {
_unpause();
}
// ── Views ────────────────────────────────────────────────────────────
/// @inheritdoc ICuratorModule
function poolBalance(uint256 classId) external view returns (uint256) {
return _storage().pools[classId].balance;
}
/// @inheritdoc ICuratorModule
function unresolvedDefaults(uint256 classId) external view returns (uint256) {
return _storage().unresolvedDefaults[classId];
}
/// @inheritdoc ICuratorModule
/// @dev AUDIT FIX (SWEEP-4 S4-R1, FOUR-INPUT COMPOSITION). A live-round stake is exact. A
/// stale closed-round stake is a conservative pre-settlement quote: the executable
/// `claimClosedRound` path divides one shared remaining/remaining snapshot and therefore
/// depends on which holder settles first, information a per-holder view cannot know.
/// Rounding every independent stale quote up can make their aggregate exceed the pool;
/// the view therefore rounds down except for the unique stake that owns the snapshot's
/// entire remaining denominator. That whole-cohort claimant may receive the same one-unit
/// remainder as executable settlement without making aggregate quotes exceed the pool.
/// Settlement still keeps every non-zero residual reachable, and its post-write
/// `_notifyPoints` publishes the exact live value.
function postedOf(uint256 classId, address curator) external view returns (uint256) {
CuratorStorage storage $ = _storage();
ClassPool storage pool = $.pools[classId];
(uint256 shares, bool live) = _settledShares($, classId, pool, $.stakes[classId][curator]);
if (!live || pool.totalShares == 0) return 0;
return Math.mulDiv(shares, pool.balance, pool.totalShares);
}
/// @inheritdoc ICuratorModule
function closedRound(uint256 classId, uint256 round)
external
view
returns (uint256 closedShares, uint256 carriedShares)
{
ClosedRound storage snap = _storage().closedRounds[classId][round];
return (snap.shares, snap.carriedShares);
}
/// @inheritdoc ICuratorModule
function requiredFirstLoss(uint256 classId) public view returns (uint256) {
CuratorStorage storage $ = _storage();
return _requiredFirstLoss($, classId);
}
/// @inheritdoc ICuratorModule
function headroom(uint256 classId) external view returns (uint256) {
CuratorStorage storage $ = _storage();
return _headroom($, classId, $.pools[classId]);
}
/// @inheritdoc ICuratorModule
function firstLossTarget(uint256 classId) external view returns (uint256) {
return _storage().targets[classId];
}
/// @inheritdoc ICuratorModule
function isApprovedCurator(uint256 classId, address curator) external view returns (bool) {
return _storage().approved[classId][curator];
}
/// @notice Wired module addresses (post-deploy validation aid).
function modules() external view returns (address usdfr, address registry, address feeVault) {
CuratorStorage storage $ = _storage();
return (address($.usdfr), address($.registry), address($.feeVault));
}
/// @notice Current share round for a class pool (advances on full wipe-out).
function poolRound(uint256 classId) external view returns (uint256) {
return _storage().pools[classId].round;
}
/// @notice Total internal shares for a class pool. Always >= `poolBalance` (the
/// share price never exceeds 1 — see the note in `postFirstLoss`).
function poolShares(uint256 classId) external view returns (uint256) {
return _storage().pools[classId].totalShares;
}
// ── Internals ────────────────────────────────────────────────────────
/// @dev AUDIT FIX (SWEEP-3 S3-F1) — LOAD-BEARING, DO NOT DELETE OR INLINE AWAY.
/// Advances the class share round when the pool is EFFECTIVELY wiped, i.e. when its share
/// price has fallen to or below 1e-18 (`balance * MAX_SHARE_INFLATION <= totalShares`).
/// The full statement of the defect, the attacker's exact control over the residual, the
/// measured brick, and the derivation of both the constant and the dust bound are in the
/// block on `postFirstLoss`. Read that before touching this.
///
/// IT IS CALLED FROM `postFirstLoss` AND FROM NOWHERE ELSE — in particular NOT from
/// `absorbLoss`/`absorbGlobalLoss`. See "WHY THE NORMALISATION IS LAZY" in `postFirstLoss`
/// for the measurement that settled that.
///
/// SETTING `totalShares = balance` (NOT ZERO) IS PART OF THE FIX. Zero would mint
/// `shares == amount` against `balance == amount + residual` on the next post, pushing the
/// share price ABOVE 1 and breaking this contract's shipped share-price invariant. At
/// `totalShares == balance` the price is exactly 1 and the forfeited residual stands as
/// UNOWNED backing that absorbs before any curator's capital.
///
/// Falsified by `test_S3_F1_layerOneMustStillBeReFundableAfterNearTotalExitDraws`,
/// `test_S3_F1_theFacilityRouteInflatesTheShareRatioIdentically` and
/// `test_S3_F1_oneExitDrawCanCollapseTheShareRatioInEveryClassAtOnce`.
///
/// AUDIT FIX (SWEEP-4 S4-R1) — THE SNAPSHOT WRITE IS A GUARD, NOT BOOKKEEPING. Deleting it
/// restores the shipped forfeiture and reds
/// `test_S4_R1_aRoundCloseMustNotForfeitTheSurvivingResidual`. The `residual != 0` test is
/// what keeps the exact-wipe case (`balance == 0`) writing nothing at all: there is
/// genuinely no claim to carry there, and a zero-valued snapshot would be indistinguishable
/// from "never closed".
function _advanceRoundIfWiped(CuratorStorage storage $, uint256 classId, ClassPool storage pool) private {
uint256 shares = pool.totalShares;
uint256 residual = pool.balance;
if (shares == 0 || residual > shares / MAX_SHARE_INFLATION) return;
uint256 closing = pool.round;
if (residual != 0) {
// The new round opens with `totalShares == residual` (price exactly 1) and those shares
// are minted with no owner. Record that the CLOSING cohort owns them, pro-rata to the
// shares they held in the round that just closed.
ClosedRound storage snap = $.closedRounds[classId][closing];
snap.shares = shares;
snap.carriedShares = residual;
snap.shareScale = pool.shareScale;
snap.carriedScale = pool.shareScale;
emit ClosedRoundSnapshotted(classId, closing, residual, shares, residual);
}
pool.round = closing + 1;
pool.totalShares = residual;
emit PoolRoundAdvanced(classId, closing + 1);
}
/// @dev AUDIT FIX (SWEEP-4 S4-R1) — LOAD-BEARING, DO NOT DELETE OR SIMPLIFY BACK TO
/// `stake.shares = 0`. Converts a stale-round stake into its pro-rata slice of the
/// SUCCEEDING round's shares, using the snapshot `_advanceRoundIfWiped` took at the close.
///
/// REMAINING / REMAINING. Both snapshot fields are decremented by exactly what this
/// settlement takes, so the holders who have not settled always divide the carried shares
/// that have not been handed out. `Math.mulDiv` floors, so the arithmetic can never hand
/// out more than the normalized carry and the rounding dust stays unowned in the pool — the same
/// direction `withdrawFirstLoss`'s ceil rounding favours. `snap.shares` starts at the
/// closing round's ENTIRE `totalShares`, which is an upper bound on the sum of every stake
/// in that round, so the subtraction cannot underflow; it is left CHECKED so that a future
/// change breaking that bound fails loudly instead of silently over-distributing.
///
/// IT WALKS, AND THE WALK IS NOT OPTIONAL — MEASURED. Carried shares stay UNOWNED in the
/// pool until claimed, so when the succeeding round closes in its turn they are carried
/// again: a stake that slept through N closes needs N conversions. A single-hop version of
/// this function reds `test_S3_F1_layerOneMustStillBeReFundableAfterNearTotalExitDraws` —
/// the second curator's claim converts to exactly ONE share at the first close, is
/// therefore not zero, and is then stranded two rounds behind while `postFirstLoss`
/// refuses. That is the very liveness property S3-F1 exists to protect, so the walk is
/// what keeps this fix from re-opening the finding it is layered on.
///
/// BOUNDED, BECAUSE AN UNBOUNDED WALK IS A GAS BRICK ON THE SAME LIVENESS PATH. Closes are
/// permissionless in effect (any KYC'd redeemer can drive the ADR-0034 Y-bis draw), so the
/// chain length is not the curator's to control and must not be able to grow a
/// `postFirstLoss` past the block gas limit. `MAX_CLOSED_ROUND_HOPS` bounds one call;
/// a longer chain is still fully recoverable because `claimClosedRound` KEEPS the progress
/// of every hop it makes and may be called repeatedly.
///
/// RETURNS `false` RATHER THAN REVERTING, and the distinction is the whole design.
/// Reverting here would undo the hops this call just made and no sequence of calls could
/// ever make progress. Callers that are about to change the stake's value
/// (`postFirstLoss`, `withdrawFirstLoss`) turn the `false` into
/// `Curator_UnsettledClosedRound` — refusing rather than erasing — while `claimClosedRound`
/// simply keeps the hops, so walking the chain terminates.
///
/// THE `shares == 0` EXIT IS NOT AN OPTIMISATION. Each hop multiplies a stake by a factor
/// of at most 1e-18 (that is the close condition), so a claim that has floored to zero is
/// zero at every later round too. Jumping such a stake straight to the live round is what
/// keeps the ordinary case — a genuinely wiped stake, which is most of them — a single
/// transaction with no chain to walk. A `snapShares == 0` hop is the same statement for the
/// exact-wipe case, where no snapshot was ever written because nothing survived to carry.
function _settleStaleRound(
CuratorStorage storage $,
uint256 classId,
ClassPool storage pool,
address curator,
CuratorStake storage stake
) private returns (bool complete) {
uint256 liveRound = pool.round;
uint256 fromRound = stake.round;
if (fromRound == liveRound) return true;
uint256 shares = stake.shares;
uint256 sharesScale = stake.shareScale;
if (shares == 0) {
stake.round = liveRound;
stake.shareScale = pool.shareScale;
return true;
}
uint256 staleShares = shares;
uint256 round_ = fromRound;
for (uint256 hops = 0; round_ != liveRound && hops < MAX_CLOSED_ROUND_HOPS; ++hops) {
ClosedRound storage snap = $.closedRounds[classId][round_];
uint256 snapShares = snap.shares;
if (snapShares == 0) {
shares = 0; // the round closed on an exact wipe: there was nothing to carry
break;
}
// A pool normalization may have reduced the aggregate share units since this stake
// was written. Snapshots carry their own scale; convert the stale stake before
// decrementing the snapshot denominator, otherwise a lazy old stake can exceed the
// denominator and panic on the subtraction.
shares = _rescaleClosedShares(shares, sharesScale, snap.shareScale);
sharesScale = snap.shareScale;
if (shares == 0) break;
if (shares > snapShares) shares = snapShares;
sharesScale = _nextRoundScale($, classId, pool, round_);
shares = _takeClosedCarry(snap, shares, sharesScale);
round_ += 1;
if (shares == 0) break;
}
if (shares == 0) round_ = liveRound;
if (shares != 0 && round_ == liveRound) {
shares = _rescaleClosedShares(shares, sharesScale, pool.shareScale);
sharesScale = pool.shareScale;
}
if (shares == 0) {
round_ = liveRound;
sharesScale = pool.shareScale;
}
stake.shares = shares;
stake.round = round_;
stake.shareScale = sharesScale;
emit ClosedRoundSettled(classId, curator, fromRound, round_, staleShares, shares);
return round_ == liveRound;
}
function _postedOf(ClassPool storage pool, CuratorStake storage stake) private view returns (uint256) {
if (stake.round != pool.round || pool.totalShares == 0) return 0;
return Math.mulDiv(_currentStakeShares(pool, stake), pool.balance, pool.totalShares);
}
/// @dev Closed-round conversion uses a ceiling when a lazy scale rebase would otherwise
/// erase a non-zero stale stake. That one-unit floor is bounded by the snapshot carry;
/// ordinary live-round normalization continues to use the loss-favouring floor below.
function _rescaleClosedShares(uint256 shares, uint256 fromScale, uint256 toScale) private pure returns (uint256) {
if (fromScale == toScale || shares == 0) return shares;
if (fromScale > toScale) {
uint256 downshift = fromScale - toScale;
if (downshift >= 256 || shares > type(uint256).max >> downshift) {
revert Curator_ShareCapacityExceeded(shares, type(uint256).max);
}
return shares << downshift;
}
return _ceilScaleDown(shares, toScale - fromScale);
}
function _ceilScaleDown(uint256 shares, uint256 shift) private pure returns (uint256) {
if (shares == 0) return 0;
if (shift >= 256) return 1;
return Math.ceilDiv(shares, uint256(1) << shift);
}
function _nextRoundScale(CuratorStorage storage $, uint256 classId, ClassPool storage pool, uint256 round_)
private
view
returns (uint256)
{
return round_ + 1 == pool.round ? pool.shareScale : $.closedRounds[classId][round_ + 1].shareScale;
}
function _takeClosedCarry(ClosedRound storage snap, uint256 oldShares, uint256 nextScale)
private
returns (uint256 converted)
{
// Normalize the SHARED remaining inventory, not each claimant's output. In the
// saved A-12 sequence a 2-share carry and a 2-share live stake became one total
// share after a fourfold normalization. The old code rounded each old claimant
// back up to one, adding a claim beyond that single normalized share.
uint256 carryScale = snap.carriedScale == 0 ? snap.shareScale : snap.carriedScale;
if (nextScale > carryScale) {
snap.carriedShares = _ceilScaleDown(snap.carriedShares, nextScale - carryScale);
snap.carriedScale = nextScale;
}
uint256 carry = snap.carriedShares;
converted = Math.mulDiv(oldShares, carry, snap.shares);
if (converted == 0 && carry != 0) converted = 1;
if (converted > carry) converted = carry;
snap.shares -= oldShares;
snap.carriedShares = carry - converted;
}
/// @dev Keeps the aggregate share ratio representable without iterating curators. The
/// aggregate rounds up and holders round down, so normalization cannot create value.
function _normalizePoolShares(uint256 classId, ClassPool storage pool) private returns (bool normalized) {
if (pool.balance == 0 || pool.totalShares == 0) return false;
uint256 ratio = pool.totalShares / pool.balance;
if (ratio < 2) return false;
uint256 shift = Math.log2(ratio);
if (shift == 0) return false;
uint256 divisor = uint256(1) << shift;
pool.totalShares = Math.ceilDiv(pool.totalShares, divisor);
pool.shareScale += shift;
emit PoolSharesNormalized(classId, shift, pool.totalShares);
return true;
}
function _currentStakeShares(ClassPool storage pool, CuratorStake storage stake) private view returns (uint256) {
uint256 shift = pool.shareScale - stake.shareScale;
if (shift >= 256) return 0;
return stake.shares >> shift;
}
function _syncStakeShares(ClassPool storage pool, CuratorStake storage stake) private {
if (stake.shareScale == pool.shareScale) return;
stake.shares = _currentStakeShares(pool, stake);
stake.shareScale = pool.shareScale;
}
/// @dev AUDIT FIX (SWEEP-4 S4-R1, FOUR-INPUT COMPOSITION). Read-only projection used by
/// `postedOf`. It follows the same round chain and hop bound as `_settleStaleRound`, but it
/// floors stale conversions for independent partial holders instead of applying that
/// write path's one-unit residual minimum to every quote. Several independent views all
/// see the same undecremented snapshot, so rounding each one up produces a non-executable
/// aggregate above the pool. The unique stake equal to the snapshot's entire remaining
/// denominator is the exception: it alone may receive the one-unit remainder, which is
/// aggregate-safe and preserves a sole claimant across a chain of closes. Any other
/// conservative zero remains claimable through `claimClosedRound`, which writes the exact
/// live stake and notifies Points.
function _settledShares(
CuratorStorage storage $,
uint256 classId,
ClassPool storage pool,
CuratorStake storage stake
) private view returns (uint256 shares, bool live) {
uint256 liveRound = pool.round;
uint256 round_ = stake.round;
shares = stake.shares;
uint256 sharesScale = stake.shareScale;
bool receivesRemainder;
if (round_ == liveRound) return (_currentStakeShares(pool, stake), true);
if (shares == 0) return (0, true);
for (uint256 hops = 0; round_ != liveRound && hops < MAX_CLOSED_ROUND_HOPS; ++hops) {
ClosedRound storage snap = $.closedRounds[classId][round_];
uint256 snapShares = snap.shares;
if (snapShares == 0) return (0, true);
// Equality means this stake is the snapshot's whole REMAINING cohort. A one-share
// deficit is also conclusive when the denominator is > 2: aggregate normalization
// rounds `pool.totalShares` up while the sole holder rounds down, leaving exactly that
// unowned share. Two distinct positive stakes cannot both be within one of a
// denominator above two because their sum is bounded by the denominator. The tiny
// ambiguous denominators stay conservative.
bool wholeRemaining = shares == snapShares || (snapShares > 2 && shares == snapShares - 1);
if (!receivesRemainder && sharesScale == snap.shareScale && wholeRemaining) {
receivesRemainder = true;
}
shares = _rescaleClosedSharesView(shares, sharesScale, snap.shareScale, receivesRemainder);
sharesScale = snap.shareScale;
if (shares == 0) return (0, true);
if (shares > snapShares) shares = snapShares;
uint256 nextScale = _nextRoundScale($, classId, pool, round_);
// Read-side quotes cannot predict settlement order. Floor the undecremented snapshot
// conversion so independently queried holders remain aggregate-safe; only the write
// path may apply its one-unit minimum while decrementing the shared carry.
shares = _quoteClosedCarry(snap, shares, nextScale, receivesRemainder);
if (shares == 0) return (0, true);
sharesScale = nextScale;
round_ += 1;
}
if (round_ == liveRound && shares != 0) {
shares = _rescaleClosedSharesView(shares, sharesScale, pool.shareScale, receivesRemainder);
}
return (shares, round_ == liveRound);
}
function _rescaleClosedSharesView(uint256 shares, uint256 fromScale, uint256 toScale, bool receivesRemainder)
private
pure
returns (uint256)
{
if (fromScale == toScale || shares == 0) return shares;
if (fromScale > toScale) {
uint256 downshift = fromScale - toScale;
if (downshift >= 256 || shares > type(uint256).max >> downshift) return 0;
return shares << downshift;
}
uint256 upshift = toScale - fromScale;
if (upshift >= 256) return 0;
uint256 divisor = uint256(1) << upshift;
return receivesRemainder ? Math.ceilDiv(shares, divisor) : shares / divisor;
}
function _quoteClosedCarry(ClosedRound storage snap, uint256 oldShares, uint256 nextScale, bool receivesRemainder)
private
view
returns (uint256 quoted)
{
uint256 carryScale = snap.carriedScale == 0 ? snap.shareScale : snap.carriedScale;
uint256 carry = snap.carriedShares;
if (nextScale > carryScale) carry = _ceilScaleDown(carry, nextScale - carryScale);
quoted = Math.mulDiv(oldShares, carry, snap.shares);
if (quoted == 0 && carry != 0 && receivesRemainder) quoted = 1;
if (quoted > carry) quoted = carry;
}
/// @dev Subordination requirement: live exposure must stay protected up to the
/// class target. Below the target, all posted capital protecting exposure is
/// locked; a fully repaid class (zero exposure) frees everything.
///
/// ── AUDIT FIX (SWEEP-2 CSG-F1) — THE MARKED FLOOR. LOAD-BEARING, DO NOT DELETE. ──
///
/// THE TWO FORMULAS DISAGREED, AND THE SENIOR PRICE WAS THE ONE HOLDING THE SHORT END.
/// What may LEAVE was `poolBalance - min(firstLossTarget, classExposure)`. What the
/// conservative senior NAV COUNTS as cascade layer 1 is, per class,
/// `min(declaredDefaultedPrincipal + pastDuePrincipal, poolBalance)`
/// (`ConservativeImpairmentMath.pendingSeniorImpairment`). Whenever
/// `classExposure > firstLossTarget` — the ordinary steady state for any class book above
/// the `Config.DEFAULT_FIRST_LOSS_PER_CLASS` floor — the second exceeds the first, so
/// capital the senior redemption price was ALREADY EXTENDING CREDIT FOR was withdrawable.
///
/// WHY THE TWO FREEZES DID NOT COVER IT. A DECLARED default freezes the class
/// (R4-EC2 `unresolvedDefaults`); an ADR-0034 Y-bis exit draw freezes every class
/// (R6-CF1 limb 4). An UNATTESTED PAST-DUE MARK freezes NOTHING — `markPastDue`'s NatSpec
/// says so deliberately, because "a reversible past-due mark must not freeze first-loss" —
/// and it does not move `totalBackingValue()`, so limb 4 reads false as well. That is the
/// one loss path with no freeze at all, and it is exactly the path that credits layer 1.
///
/// MEASURED (SWEEP-2 CSG-F1, HIGH): with a 350,000e18 past-due mark standing and no
/// freeze armed, a curator withdrew 800,000e18 of layer-1 capital with no revert and the
/// senior redemption price fell 1,000,000e18 -> 650,000e18. The discriminating control is
/// that the IDENTICAL withdrawal on the IDENTICAL shape reverts `Curator_ClassDefaultFrozen`
/// once the same mark is attested.
///
/// WHY A FLOOR AND NOT A FREEZE. Freezing on `markPastDue` would hand a griefing lever to
/// whoever can mark a facility past due — the sting the H-5 redesign deliberately closed.
/// A floor locks ONLY the capital the mark itself credits, never the whole pool and never
/// the class, so `markPastDue` stays non-freezing while the conservative NAV stops
/// crediting capital that can walk out from under it. It also closes the one-call route
/// in: `setFirstLossTarget` has no lower bound, and before this a single governance call
/// lowering the target manufactured 800,000e18 of headroom out of credited capital.
///
/// THE PERMISSIONLESS-MARK TRADE-OFF, STATED SO IT IS NOT DISCOVERED LATE. `markPastDue`
/// is permissionless, so a bystander CAN now lock curator capital — up to, and only up to,
/// the principal the mark itself puts at risk. That is not griefing: the call reverts
/// unless the facility is genuinely past its `nextPaymentDue` plus its class grace window,
/// and the same permissionless mark ALREADY depresses the senior redemption price by the
/// same principal (H-5's design). Locking exactly what it credits is the consistent
/// position; leaving it withdrawable was not. The lock is temporary and has two ordinary
/// exits — `clearPastDue` (SERVICER, on cure evidence) and the facility simply repaying —
/// plus the declared-default path, which supersedes it with the R4-EC2 class freeze.
///
/// SOFT-DEFAULTS TO THE OLD FORMULA WHEN THE CREDIT BOOK IS UNREACHABLE, and that is safe
/// HERE and only here: `withdrawFirstLoss` reverts `Curator_ReserveNotWired` before it
/// ever reads this, so the degraded answer is reachable only through the `headroom()` /
/// `requiredFirstLoss()` VIEWS, which must not revert on a partially wired deployment.
function _requiredFirstLoss(CuratorStorage storage $, uint256 classId) private view returns (uint256) {
uint256 exposure = $.registry.classExposure(classId);
uint256 target = $.targets[classId];
uint256 required = exposure < target ? exposure : target;
uint256 marked = _markedFirstLoss($, classId);
return marked > required ? marked : required;
}
/// @dev AUDIT FIX (SWEEP-2 CSG-F1). The per-class layer-1 credit the conservative senior NAV is
/// currently extending, read from the SAME source of truth the NAV reads:
/// `declaredDefaultedPrincipal(classId) + pastDuePrincipal(classId)` on the wired loss
/// absorber. Mirroring the NAV's own expression is the point — two enumerations of the
/// same quantity that do not agree is how this defect existed (see SEAM-1). If
/// `ConservativeImpairmentMath`'s layer-1 term ever changes, CHANGE THIS WITH IT.
///
/// No new storage: the absorber is reached through the already-wired `reserves`
/// (`IReserveManager.lossAbsorber()`), so `CuratorStorage`'s append-only tail is
/// untouched and both storage-layout gates stay green.
///
/// The NAV clamps this at `poolBalance`; clamping here would be redundant because
/// `_headroom` already floors at zero.
///
/// IT FAILS CLOSED, AND IT DOES SO WITHOUT REVERTING — BOTH HALVES ARE DELIBERATE.
/// `ReserveManager.setLossAbsorber` validates only `reserveLossSource()`, so a mis-wired
/// or not-yet-upgraded absorber can be present and unable to answer these two getters.
/// "Cannot tell" must not read as "nothing is credited" — that is the same reasoning
/// `custodyFreezeActive()` states for its own unwired case — so an unreadable book locks
/// the pool (`_UNREADABLE_BOOK_LOCK`, unreachably above any pool balance, so
/// `_headroom` floors at zero). It is a RAW length-checked staticcall rather than a plain
/// interface call because `headroom()` and `requiredFirstLoss()` are read by
/// `Validate.s.sol`, by dashboards and by the invariant oracles: a revert there is a worse
/// failure mode than a loud sentinel, and it is NOT `try`/`catch` for the reason
/// `_liveGovernancePath` documents at length — a permissive fallback answers with SUCCESS
/// and EMPTY returndata, and Solidity's `catch` does not catch the `abi.decode` failure
/// that follows.
///
/// A ZERO absorber is the exception and returns 0, not the lock: that is the state every
/// deployment starts in, and locking there would brick first-loss withdrawal on a
/// partially wired stack. `withdrawFirstLoss` already refuses outright while `reserves`
/// itself is unwired (`Curator_ReserveNotWired`), and `custodyFreezeActive()` returns
/// true — hence freezes — while the absorber is unset.
function _markedFirstLoss(CuratorStorage storage $, uint256 classId) private view returns (uint256) {
IReserveManager reserves = $.reserveManager;
if (address(reserves) == address(0)) return 0;
address book = reserves.lossAbsorber();
if (book == address(0)) return 0;
(bool okDeclared, uint256 declared) =
_readClassPrincipal(book, IConservativeImpairmentBook.declaredDefaultedPrincipal.selector, classId);
(bool okPastDue, uint256 pastDue) =
_readClassPrincipal(book, IConservativeImpairmentBook.pastDuePrincipal.selector, classId);
if (!okDeclared || !okPastDue) return _UNREADABLE_BOOK_LOCK;
unchecked {
// Both legs are principal balances bounded by the book; their sum cannot overflow.
return declared + pastDue;
}
}
/// @dev AUDIT FIX (SWEEP-2 CSG-F1). One length-checked raw staticcall. Returns `(false, 0)` on
/// a revert, on empty returndata (the permissive-fallback case), or on anything that is
/// not exactly one word — never a decoded value from data too short to hold one.
function _readClassPrincipal(address book, bytes4 selector, uint256 classId)
private
view
returns (bool ok, uint256 value)
{
(bool success, bytes memory data) = book.staticcall(abi.encodeWithSelector(selector, classId));
if (!success || data.length != 32) return (false, 0);
return (true, abi.decode(data, (uint256)));
}
function _headroom(CuratorStorage storage $, uint256 classId, ClassPool storage pool)
private
view
returns (uint256)
{
uint256 required = _requiredFirstLoss($, classId);
return pool.balance > required ? pool.balance - required : 0;
}
/// @dev Notifies the points module of the curator's new posted first-loss (P-01).
/// Uses `PointsHookGas` classification (matching `USDfr`/`sUSDfr`, CORR-DELTA-02):
/// caller-starved gas (insufficient epilogue reserve or an empty-data failure below
/// `FAILURE_CLASSIFICATION_GAS`) reverts `PointsHook_InsufficientGas` so a curator
/// cannot withdraw with tight gas and retain phantom points. Legacy post-install code
/// disappearance, non-empty reverts, and sufficiently funded empty failures remain
/// fail-open with zero returndata copy and fixed failure telemetry.
function _notifyPoints(CuratorStorage storage $, uint256 classId, address curator) private {
IPointsModule pm = $.pointsModule;
address module = address(pm);
if (module == address(0)) return;
uint256 posted = _postedOf($.pools[classId], $.stakes[classId][curator]);
bytes memory data = abi.encodeCall(pm.onCuratorStakeChange, (curator, classId, posted));
if (module.code.length == 0) {
emit CuratorPointsHookFailed(module, bytes4(data), classId, curator, 0);
return;
}
uint256 hookGas = PointsHookGas.hookGasLimit();
bool ok = false;
uint256 returnSize = 0;
assembly ("memory-safe") {
ok := call(hookGas, module, 0, add(data, 32), mload(data), 0, 0)
returnSize := returndatasize()
}
if (!ok) {
PointsHookGas.requireSafeFailure(hookGas, returnSize);
emit CuratorPointsHookFailed(module, bytes4(data), classId, curator, hookGas);
}
}
/// @dev Observer-only loss hook: cap gas at `LOSS_POINTS_HOOK_GAS`, retain all mandatory
/// work, copy no returndata, and stay unconditionally fail-open so a broken points
/// module can never block the never-pausable loss cascade.
function _callLossPoints(IPointsModule points, bytes memory data, uint256 classId, uint256 followingReserve)
private
{
address module = address(points);
bool hasCode = module.code.length != 0;
uint256 retained = POINTS_HOOK_EPILOGUE_GAS + POINTS_HOOK_CALL_PREPARATION_GAS + followingReserve;
uint256 available = gasleft();
uint256 hookGas = 0;
if (hasCode && available > retained) {
hookGas = available - retained;
if (hookGas > LOSS_POINTS_HOOK_GAS) hookGas = LOSS_POINTS_HOOK_GAS;
}
bool ok = false;
if (hookGas != 0) {
assembly ("memory-safe") {
ok := call(hookGas, module, 0, add(data, 32), mload(data), 0, 0)
}
}
if (!ok) emit CuratorPointsHookFailed(module, bytes4(data), classId, address(0), hookGas);
}
/// @dev AUDIT FIX (F3-PA-c). The governance path the pre-arm must outlast, UNBOUNDED except
/// for overflow safety: the longer of the preserved ten-day `Config` floor and the live reading.
/// `custodyPreArmGovernancePath()` is this value bounded by `CUSTODY_PRE_ARM_MAX_PATH`;
/// the difference between the two is exactly what
/// `custodyPreArmCoversLiveGovernancePath()` reports.
function _governancePath() private view returns (uint256) {
uint256 path = Config.CURATOR_PRE_ARM_MIN_GOVERNANCE_PATH;
uint256 live = _liveGovernancePath(_storage().governor);
return live > path ? live : path;
}
/// @dev AUDIT FIX (F3-PA-c). Single derivation for every pre-arm view and for the arm itself,
/// so the live governance reads happen ONCE per call and the three published quantities
/// can never disagree with each other within a transaction.
///
/// THE LAST LINE IS A GUARD. `duration > boundedPath` is what the whole mechanism rests
/// on; with `CUSTODY_PRE_ARM_MAX_DURATION == CUSTODY_PRE_ARM_MAX_PATH * 3 / 2` the clamp
/// cannot bind, and the `+ 1` cannot fire for any path at or above the `Config` floor of
/// ten days. Both stay because the property must hold by construction and not by
/// arithmetic that a future constant change could quietly falsify.
function _derivePreArm() private view returns (uint256 livePath, uint64 duration) {
livePath = _governancePath();
uint256 bounded = livePath > CUSTODY_PRE_ARM_MAX_PATH ? uint256(CUSTODY_PRE_ARM_MAX_PATH) : livePath;
uint256 derived = bounded + bounded / 2;
if (derived > CUSTODY_PRE_ARM_MAX_DURATION) derived = CUSTODY_PRE_ARM_MAX_DURATION;
if (derived <= bounded) derived = bounded + 1;
duration = uint64(derived);
}
/// @dev AUDIT FIX (R6-CF1). Live `votingDelay + votingPeriod + timelock minDelay`, in SECONDS,
/// or zero when it cannot be read commensurably. Zero is safe: the caller keeps the
/// `Config` floor, which is never shorter than the launch governance path.
///
/// AUDIT FIX (F3-PA-d) — WHY THERE IS NO `try`/`catch` HERE ANY MORE, AND WHY IT MUST NOT
/// COME BACK. R6-CF1 read these four values through `try`/`catch` and asserted in its own
/// comment that the leading `code.length` check made that safe. IT DOES NOT. `code.length`
/// only proves the address is a contract; it says nothing about the callee's ANSWER. A
/// governor with a permissive fallback — a proxy whose implementation slot is empty, a
/// Safe, anything with `fallback() external {}` — answers `CLOCK_MODE()` with SUCCESS and
/// EMPTY returndata, and Solidity's `try`/`catch` does NOT catch the `abi.decode` failure
/// that follows (measured: the decode revert escapes the inner `catch` entirely). That
/// reverted `custodyPreArmDuration()` and through it `preArmCustodyFreeze()` — disarming
/// the guardian exactly when it is needed, which is the failure mode the original comment
/// was written to rule out.
///
/// Every read is therefore a RAW staticcall whose returndata length is checked BEFORE any
/// decode, and each defence is load-bearing:
/// - `data.length != 32` rejects empty and short returndata; the surviving 32 bytes
/// decode as a `uint256` unconditionally, so no decode can revert.
/// - an address term is range-checked against `type(uint160).max` rather than decoded as
/// `address`, because `abi.decode(..., (address))` reverts on dirty high bits.
/// - the clock mode is compared as RETURNDATA against the canonical ABI encoding, so a
/// hostile dynamic-type header can never steer a decode. It is checked at all because
/// `votingDelay`/`votingPeriod` are denominated in the governor's ERC-6372 clock, and
/// adding BLOCK counts to `block.timestamp` is wrong by orders of magnitude.
/// - `GOV_READ_GAS` bounds each sub-call so a gas-burning governor cannot take the
/// guardian's arm down with it.
/// - each term is capped before summing so a hostile parameter cannot overflow.
function _liveGovernancePath(address governor_) private view returns (uint256) {
if (governor_ == address(0) || governor_.code.length == 0) return 0;
if (!_clockIsTimestamp(governor_)) return 0;
(bool okDelay, uint256 delay_) = _readUint(governor_, IGovernanceSchedule.votingDelay.selector);
if (!okDelay) return 0;
(bool okPeriod, uint256 period_) = _readUint(governor_, IGovernanceSchedule.votingPeriod.selector);
if (!okPeriod) return 0;
(bool okTimelock, uint256 rawTimelock) = _readUint(governor_, IGovernanceSchedule.timelock.selector);
if (!okTimelock || rawTimelock > type(uint160).max) return 0;
address timelock_ = address(uint160(rawTimelock));
if (timelock_.code.length == 0) return 0;
(bool okMin, uint256 minDelay_) = _readUint(timelock_, ITimelockSchedule.getMinDelay.selector);
if (!okMin) return 0;
return _capTerm(delay_) + _capTerm(period_) + _capTerm(minDelay_);
}
/// @dev AUDIT FIX (F3-PA-d). Gas-bounded, length-checked word read. Returns `ok == false`
/// rather than reverting for EVERY failure mode a foreign address can present: revert,
/// out-of-gas, empty returndata, short returndata, over-long returndata.
function _readUint(address target, bytes4 selector) private view returns (bool ok, uint256 value) {
(bool success, bytes memory data) = target.staticcall{gas: GOV_READ_GAS}(abi.encodeWithSelector(selector));
if (!success || data.length != 32) return (false, 0);
return (true, abi.decode(data, (uint256)));
}
/// @dev AUDIT FIX (F3-PA-d). ERC-6372 clock check by RETURNDATA EQUALITY. Comparing the raw
/// bytes against the canonical ABI encoding of `"mode=timestamp"` means a governor that
/// returns nothing, garbage, or a malformed dynamic-type header simply fails the check and
/// falls back to the `Config` floor — it can never revert this call.
function _clockIsTimestamp(address governor_) private view returns (bool) {
(bool success, bytes memory data) =
governor_.staticcall{gas: GOV_READ_GAS}(abi.encodeWithSelector(IGovernanceSchedule.CLOCK_MODE.selector));
if (!success) return false;
return keccak256(data) == keccak256(abi.encode(CLOCK_MODE_TIMESTAMP));
}
/// @dev AUDIT FIX (F3-PA-c). Overflow guard on a single governance term. `type(uint64).max`
/// rather than `CUSTODY_PRE_ARM_MAX_DURATION`: capping each term at the DURATION ceiling
/// was what let three capped terms sum past it and then be silently truncated. The path
/// is bounded once, as a whole, in `_derivePreArm`.
function _capTerm(uint256 term) private pure returns (uint256) {
return term > type(uint64).max ? uint256(type(uint64).max) : term;
}
function _requireKnownClass(uint256 classId) private pure {
if (classId == 0 || classId > Config.NUM_CLASSES) revert Curator_UnknownClass(classId);
}
function _authorizeUpgrade(address) internal override onlyRole(Roles.UPGRADER_ROLE) {}
function _storage() private pure returns (CuratorStorage storage $) {
assembly {
$.slot := CURATOR_STORAGE_LOCATION
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
struct AccessControlStorage {
mapping(bytes32 role => RoleData) _roles;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;
function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
assembly {
$.slot := AccessControlStorageLocation
}
}
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
AccessControlStorage storage $ = _getAccessControlStorage();
bytes32 previousAdminRole = getRoleAdmin(role);
$._roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (!hasRole(role, account)) {
$._roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (hasRole(role, account)) {
$._roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reinitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
*
* NOTE: Consider following the ERC-7201 formula to derive storage locations.
*/
function _initializableStorageSlot() internal pure virtual returns (bytes32) {
return INITIALIZABLE_STORAGE;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
bytes32 slot = _initializableStorageSlot();
assembly {
$.slot := slot
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.22;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC-1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Pausable
struct PausableStorage {
bool _paused;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;
function _getPausableStorage() private pure returns (PausableStorage storage $) {
assembly {
$.slot := PausableStorageLocation
}
}
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
function __Pausable_init() internal onlyInitializing {
}
function __Pausable_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
PausableStorage storage $ = _getPausableStorage();
return $._paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
emit Unpaused(_msgSender());
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// On the first call to nonReentrant, _status will be NOT_ENTERED
if ($._status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
$._status = ENTERED;
}
function _nonReentrantAfter() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
$._status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165Upgradeable is Initializable, IERC165 {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
lib/openzeppelin-contracts/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)
pragma solidity >=0.8.4;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted to signal this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1967.sol)
pragma solidity >=0.4.11;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC4626.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*/
interface IERC4626 is IERC20, IERC20Metadata {
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/**
* @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
*
* - MUST be an ERC-20 token contract.
* - MUST NOT revert.
*/
function asset() external view returns (address assetTokenAddress);
/**
* @dev Returns the total amount of the underlying asset that is “managed” by Vault.
*
* - SHOULD include any compounding that occurs from yield.
* - MUST be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT revert.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
* through a deposit call.
*
* - MUST return a limited value if receiver is subject to some deposit limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
* - MUST NOT revert.
*/
function maxDeposit(address receiver) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
* call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
* in the same transaction.
* - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
* deposit would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* deposit execution, and are accounted for during deposit.
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
* - MUST return a limited value if receiver is subject to some mint limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
* - MUST NOT revert.
*/
function maxMint(address receiver) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
* same transaction.
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
* would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
* execution, and are accounted for during mint.
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, through a withdraw call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
* called
* in the same transaction.
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* withdraw execution, and are accounted for during withdraw.
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
* through a redeem call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
* in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
* same transaction.
* - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
* redemption would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* redeem execution, and are accounted for during redeem.
* - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}
lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC1822.sol)
pragma solidity >=0.4.16;
/**
* @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.21;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This library provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit IERC1967.Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit IERC1967.AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the ERC-1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit IERC1967.BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/beacon/IBeacon.sol)
pragma solidity >=0.4.16;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
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/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, bytes memory returndata) = recipient.call{value: amount}("");
if (!success) {
_revert(returndata);
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
revert(add(returndata, 0x20), mload(returndata))
}
} else {
revert Errors.FailedCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
lib/openzeppelin-contracts/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
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);
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
src/interfaces/ICollateralRegistry.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title ICollateralRegistry
/// @notice Per-vertical collateral-class parameters and book-level concentration
/// accounting (ADR-0003 as amended: five classes at genesis, one of which is
/// marked-to-market per ADR-0015).
interface ICollateralRegistry {
/// @notice How a class's collateral behaves — drives valuation and remedy paths.
enum CollateralModel {
Receivable, // legal-enforcement remedies (UCC foreclosure, secondary sale)
MarkedToMarket // margin-call / liquidation remedies (ADR-0015)
}
struct ClassParams {
string name;
CollateralModel model;
bool active;
uint16 maxLtvBps; // draw ceiling (initial LTV for MTM classes)
uint64 maxMaturity; // seconds from origination
uint16 concentrationLimitBps; // max share of total book in this class
// ── marked-to-market extension (zero for receivable classes) ──────
uint16 marginCallLtvBps; // breach → MarginCalled + cure window
uint16 liquidationLtvBps; // breach / cure expiry → LiquidationInitiated
uint64 maxMarkAge; // valuation freshness bound (seconds)
}
event ClassSet(uint256 indexed classId);
event ExposureRecorded(uint256 indexed classId, bytes32 indexed borrowerId, bytes32 indexed stateId, int256 delta);
/// @notice Emitted alongside `ExposureRecorded` when the increase came from PIK capitalisation
/// rather than from an origination, so the two are distinguishable in the event stream.
/// @dev Origination exposure is a decision somebody made and an admission check passed.
/// Capitalised exposure is arithmetic on a term already agreed. A reader reconciling the
/// book needs to tell them apart, and `ExposureRecorded` alone cannot.
event CapitalizedExposureRecorded(
uint256 indexed classId, bytes32 indexed borrowerId, bytes32 indexed stateId, uint256 principal
);
event BorrowerLimitSet(uint16 limitBps);
/// @notice Governance set a per-borrower concentration limit overriding the global one.
/// @param borrowerId The borrower key.
/// @param limitBps The borrower's own max share of the book, in bps.
event BorrowerLimitOverrideSet(bytes32 indexed borrowerId, uint16 limitBps);
/// @notice Governance removed a per-borrower override; the global limit applies again.
/// @param borrowerId The borrower key.
event BorrowerLimitOverrideCleared(bytes32 indexed borrowerId);
event StateLimitSet(uint16 limitBps);
event ConcentrationFloorSet(uint256 floor);
/// @notice Governance changed the forward weight of an UNATTESTED past-due mark
/// (OWNER DECISION 2026-08-07).
/// @param bps The new weight, in bps of the executable senior charge.
event PastDueWeightSet(uint256 bps);
/// @notice A class crossed FROM within its concentration limit TO above it
/// (AUDIT FIX M-02). This is a book-shrink artefact: an amortising
/// repayment, a default write-down, or the retirement of an unfunded
/// facility removes exposure elsewhere, so an untouched class's SHARE of the
/// remaining book rises without that class growing. Such a decrease can never
/// be blocked (blocking it would let a concentration limit veto a loss being
/// realized, inverting the loss cascade), so the breach is reported, not
/// prevented — and no new exposure may be added to the class while it stands.
/// @param classId The class now above its limit.
/// @param exposure The class's exposure after the change (18-dec).
/// @param totalExposure The whole book's exposure after the change (18-dec).
/// @param limitBps The class's configured limit as a share of the book.
/// @param bookAboveFloor Whether the whole book is above the bootstrap floor. False
/// means this is ordinary genesis concentration on a book too small for the
/// relative limits to be the operative constraint (the absolute allowance
/// `limitBps * floor / BPS` is); alerting should filter on this rather than
/// treat a first facility at 100% of a tiny book as a risk incident.
event ConcentrationDrift(
uint256 indexed classId, uint256 exposure, uint256 totalExposure, uint16 limitBps, bool bookAboveFloor
);
/// @notice A class that was above its concentration limit is back within it — because
/// the book grew around it or its own exposure fell (AUDIT FIX M-02).
/// @param classId The class now within its limit.
/// @param exposure The class's exposure after the change (18-dec).
/// @param totalExposure The whole book's exposure after the change (18-dec).
/// @param limitBps The class's configured limit as a share of the book.
/// @param bookAboveFloor Whether the whole book is above the bootstrap floor.
event ConcentrationHealed(
uint256 indexed classId, uint256 exposure, uint256 totalExposure, uint16 limitBps, bool bookAboveFloor
);
/// @notice A borrower crossed FROM within its concentration limit TO above it
/// (AUDIT FIX M-02). Emitted for the borrower a write touches and for any id
/// passed to `syncConcentrationBreaches`; the borrower key set is unbounded and
/// not enumerable on-chain, but is fully recoverable from `ExposureRecorded`.
event BorrowerConcentrationDrift(
bytes32 indexed borrowerId, uint256 exposure, uint256 totalExposure, uint16 limitBps, bool bookAboveFloor
);
/// @notice A borrower that was above its concentration limit is back within it.
event BorrowerConcentrationHealed(
bytes32 indexed borrowerId, uint256 exposure, uint256 totalExposure, uint16 limitBps, bool bookAboveFloor
);
/// @notice A US state crossed FROM within its concentration limit TO above it.
event StateConcentrationDrift(
bytes32 indexed stateId, uint256 exposure, uint256 totalExposure, uint16 limitBps, bool bookAboveFloor
);
/// @notice A US state that was above its concentration limit is back within it.
event StateConcentrationHealed(
bytes32 indexed stateId, uint256 exposure, uint256 totalExposure, uint16 limitBps, bool bookAboveFloor
);
error Registry_UnknownClass(uint256 classId);
error Registry_ClassInactive(uint256 classId);
error Registry_BadParams();
/// @notice A configured class cannot change between receivable and marked-to-market
/// accounting. The model selects materially different valuation and remedy
/// paths and is fixed for the lifetime of a launch class.
error Registry_ModelImmutable(uint256 classId);
/// @notice The requested principal would push the book past the range in which the
/// concentration arithmetic is provably overflow-free. Fails loudly with a
/// decodable error rather than an arithmetic panic.
error Registry_PrincipalTooLarge();
/// @notice `setPastDueWeight` was asked for a weight of zero (which re-opens H-5/D5-03 by
/// disabling the only permissionless senior protection on receivables) or a weight of
/// `Config.BPS` or more (which restores the defect the weight exists to fix: an
/// unattested mark carrying the same forward weight as an attested declared default).
/// OWNER DECISION 2026-08-07. DO NOT DELETE EITHER BOUND.
/// @param bps The rejected weight.
error Registry_InvalidPastDueWeight(uint256 bps);
error Registry_ConcentrationExceeded(uint256 classId, uint256 wouldBe, uint256 limit);
error Registry_BorrowerConcentrationExceeded(bytes32 borrowerId, uint256 wouldBe, uint256 limit);
error Registry_StateConcentrationExceeded(bytes32 stateId, uint256 wouldBe, uint256 limit);
error Registry_ExposureUnderflow();
/// @notice Sets/updates a collateral class. Timelocked governance only.
/// @dev A class's collateral model is immutable after its first configuration.
function setClass(uint256 classId, ClassParams calldata p) external;
/// @notice Sets a per-borrower concentration limit overriding the global borrower limit.
function setBorrowerLimitOverride(bytes32 borrowerId, uint16 limitBps) external;
/// @notice Clears a per-borrower concentration limit override.
function clearBorrowerLimitOverride(bytes32 borrowerId) external;
/// @notice Class parameters (reverts for unknown classes).
function classParams(uint256 classId) external view returns (ClassParams memory);
/// @notice Reverts unless adding `principal` for (`classId`,`borrowerId`,`stateId`)
/// respects every concentration limit (class, borrower, state). View-only;
/// `recordExposure` performs the same checks at write time.
function checkConcentration(uint256 classId, bytes32 borrowerId, bytes32 stateId, uint256 principal)
external
view;
/// @notice Unfunded exposure already included in the ordinary registry book.
/// @dev Supplied by the bridge's complete, independently tracked Pending ledger. These
/// amounts are removed from both the funding denominator and its matching dimensions.
struct PendingExposure {
uint256 total;
uint256 classAmount;
uint256 borrowerAmount;
uint256 stateAmount;
}
/// @notice A Pending-ledger subtraction does not match the existing exposure book.
error Registry_InvalidPendingExposure();
/// @notice Checks admission against funded exposure plus the Pending facility itself.
/// @dev View-only; the bridge supplies its exact Pending ledger before any deployment.
/// Passing fabricated values to this public view grants no funding authority.
/// @param classId The facility's collateral class.
/// @param borrowerId Its authenticated borrower identity.
/// @param stateId Its state identity, or zero when not applicable.
/// @param principal The already recorded Pending principal being funded.
/// @param pending Complete Pending totals for the same identities.
function checkFundingConcentration(
uint256 classId,
bytes32 borrowerId,
bytes32 stateId,
uint256 principal,
PendingExposure calldata pending
) external view;
/// @notice Records an exposure increase (origination). Only CREDIT_ROLE (the
/// collateral/credit layer). Enforces all concentration limits.
function recordExposureIncrease(uint256 classId, bytes32 borrowerId, bytes32 stateId, uint256 principal) external;
/// @notice Records an exposure increase that came from PIK interest CAPITALISATION rather than
/// from an origination. Only CREDIT_ROLE. Books the exposure and reports every
/// concentration breach exactly as the origination path does, but does NOT revert on
/// one.
///
/// @dev WHY THIS IS NOT A HOLE IN THE CONCENTRATION LIMIT, and why it is not optional.
/// A concentration limit governs ADMISSION: it decides whether the book takes on a new
/// risk somebody chose to take. Compounding interest is not that. Nobody elects it, the
/// borrower cannot decline it, no capital moves, and the obligation was priced at
/// origination when the limit was checked. Routing it through `recordExposureIncrease`
/// meant a PIK book grew into its own limit with no adversary and then FROZE, and because
/// `ClaimBridge.nextPaymentDue` only advances inside `WaterfallEngine.capitalizePik`, the
/// freeze turned a borrower performing exactly as contracted into a permissionlessly
/// markable past-due facility, and through `DefaultManager.pastDueExposure` into pending
/// senior impairment. The protocol's own refusal became the credit event.
///
/// WHAT IS PRESERVED. The class must be known; the overflow bound that keeps the
/// concentration arithmetic safe still applies; the exposure is booked in full, which is
/// what keeps the facility WRITEABLE OFF (`realizeLoss` pairs its write-down with
/// `recordExposureDecrease`, which reverts `Registry_ExposureUnderflow` if exposure lags);
/// and every breach flag and drift event fires. Governance sees the limit crossed. The
/// limit keeps its whole observation function and loses only its ability to brick a
/// performing borrower.
///
/// `recordExposureDecrease` already carries this exact reasoning for the same reason:
/// "Reporting only - never a revert path."
///
/// WHAT THIS ADDS TO `CREDIT_ROLE`, stated because an auditor will ask. The role could
/// already move exposure in both directions: `recordExposureIncrease` upward subject to
/// the limits, and `recordExposureDecrease` downward with no check at all. This adds an
/// upward path that skips the limit, so a CREDIT_ROLE holder can now inflate a class past
/// its concentration ceiling. That moves NO VALUE - exposure is a reporting and
/// write-off-accounting quantity, not a balance - and it moves the book in the
/// CONSERVATIVE direction, making it read as more concentrated than it is. The role
/// remains a protocol-modules-only grant for the reasons recorded on
/// `recordExposureDecrease`, and this function does not change that requirement.
///
/// IF FOREST ROAD WANTS CAPITALISATION TO HARD-STOP AT THE LIMIT INSTEAD, that is a
/// one-line change back to `recordExposureIncrease` in `WaterfallEngine.capitalizePik`,
/// and it reinstates the denial of service knowingly rather than by accident.
function recordCapitalizedExposure(uint256 classId, bytes32 borrowerId, bytes32 stateId, uint256 principal)
external;
/// @notice Records an exposure decrease (repayment/writedown). Only CREDIT_ROLE.
function recordExposureDecrease(uint256 classId, bytes32 borrowerId, bytes32 stateId, uint256 principal) external;
/// @notice Current book exposure per class / borrower / state (18-dec).
function classExposure(uint256 classId) external view returns (uint256);
function borrowerExposure(bytes32 borrowerId) external view returns (uint256);
function stateExposure(bytes32 stateId) external view returns (uint256);
function totalBookExposure() external view returns (uint256);
/// @notice A class's current share of the whole book, in bps (0 on an empty book).
function classConcentrationBps(uint256 classId) external view returns (uint256);
/// @notice Whether a dimension's CURRENT share of the book exceeds its configured
/// limit — the standing disclosure fact, floor-independent (AUDIT FIX M-02).
function isOverConcentrated(uint256 classId, bytes32 borrowerId, bytes32 stateId)
external
view
returns (bool classOver, bool borrowerOver, bool stateOver);
/// @notice The 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 (OWNER DECISION 2026-08-07).
/// @dev Governed credit-risk policy, so it lives with the advance rates and concentration
/// limits rather than in DefaultManager (which is EIP-170 constrained and contended).
/// Never returns zero: an unset slot reads `Config.DEFAULT_PAST_DUE_WEIGHT_BPS`.
/// @return bps The effective weight, strictly between 0 and `Config.BPS`.
function pastDueWeightBps() external view returns (uint256 bps);
/// @notice Applies the governed unattested-past-due weight to an executable senior charge.
/// @dev Called by `DefaultManager.pendingSeniorImpairment` on the past-due cohort's charge
/// AFTER the executable bound has been applied. Rounds UP (over-mark is the safe
/// direction). OWNER DECISION 2026-08-07 — DO NOT turn this into a pass-through.
/// @param amount The executable senior charge attributable to the past-due cohort.
/// @return weighted The discounted charge that enters the conservative redemption NAV.
function weightedPastDueImpairment(uint256 amount) external view returns (uint256 weighted);
/// @notice The TOTAL conservative senior mark: the attested cohort at full weight plus the
/// unattested past-due cohort, clamped to executable capacity and ramp-weighted.
/// @dev OWNER DECISION 2026-08-07. Clamps `pastDueSenior` to the senior absorption capacity
/// `realizeLoss` could actually reach today (`vaultAssets` less the attested cohort's prior
/// claim), THEN applies the governed weight, which itself ramps from
/// `pastDueWeightBps()` back to `Config.BPS` over one `Config.DEFAULT_REDEEM_COOLDOWN`.
/// Both the CLAMP-BEFORE-WEIGHT order and the ramp's expiry are load-bearing; see the
/// implementation NatSpec.
/// @param pastDueSenior The past-due cohort's post-junior senior residual.
/// @param residual The TOTAL post-junior senior residual (both cohorts), unweighted.
/// @param vault The `sUSDfr` vault whose `totalAssets()` is layer 3's hard ceiling in
/// `realizeLoss`. Read here rather than passed in as a number so the governed weight and
/// the ceiling it is applied to stay in one timelocked module; see the implementation
/// NatSpec, which also carries the recursion warning.
/// @param anchor `DefaultManager.pastDueReliefAnchor`. ZERO (unset) fails SAFE to full weight.
/// @return mark The total conservative senior impairment entering the redemption NAV.
function conservativeSeniorMark(uint256 pastDueSenior, uint256 residual, address vault, uint256 anchor)
external
view
returns (uint256 mark);
/// @notice The forward weight, in bps, an unattested past-due mark carries after `elapsed`
/// seconds of its relief ramp (OWNER DECISION 2026-08-07).
/// @dev Ramps linearly from `pastDueWeightBps()` at `elapsed == 0` to `Config.BPS` at
/// `elapsed >= Config.DEFAULT_REDEEM_COOLDOWN`, and stays at `Config.BPS` thereafter.
/// A read-only convenience for operations and reference models; the mark itself does NOT
/// route through it (see the implementation NatSpec for why).
/// @param elapsed Seconds since `DefaultManager.pastDueReliefAnchor`.
/// @return bps The effective weight, in `[pastDueWeightBps(), Config.BPS]`.
function pastDueRampWeightBps(uint256 elapsed) external view returns (uint256 bps);
/// @notice Governance sets the forward weight of an unattested past-due mark.
/// @dev Rejects 0 (re-opens H-5/D5-03) and `Config.BPS` or more (restores the defect).
/// @param bps The new weight, strictly between 0 and `Config.BPS`.
function setPastDueWeight(uint256 bps) external;
/// @notice Bitmap of classes currently above their limit; bit `classId - 1` set.
/// @dev Recomputed from the book on every call — never served from a cached slot, so it
/// cannot report a clean book in the window after an implementation upgrade.
function overConcentratedClasses() external view returns (uint256 bitmap);
/// @notice The borrower concentration limit actually in force for `borrowerId`.
/// @dev The global limit assumes a vertical has many borrowers. A SINGLE-BORROWER vertical
/// (Digital Assets, ADR-0015) makes the class and borrower dimensions measure the same
/// exposure, so governance may set a per-borrower override. Every admission, breach
/// and headroom read routes through this same number.
/// @param borrowerId The borrower key.
/// @return limitBps The effective limit in bps.
/// @return overridden True when a per-borrower override is set.
function effectiveBorrowerLimitBps(bytes32 borrowerId) external view returns (uint16 limitBps, bool overridden);
/// @notice Whether each supplied borrower currently holds more than the per-borrower limit
/// as a share of the book — its OWN limit where one is overridden. The key set is
/// unbounded on-chain; recover it from the `ExposureRecorded` stream and pass it in.
function overConcentratedBorrowers(bytes32[] calldata borrowerIds) external view returns (bool[] memory over);
/// @notice Whether each supplied state currently holds more than the per-state limit as
/// a share of the book. Zero ids read false.
function overConcentratedStates(bytes32[] calldata stateIds) external view returns (bool[] memory over);
/// @notice Recomputes and events every concentration transition for all five classes
/// plus the supplied borrower/state ids. Permissionless: it moves no value and
/// only publishes facts the views already expose, so anyone (a keeper, a risk
/// desk, the upgrade transaction itself) can announce a standing breach without
/// waiting for the next origination or repayment.
function syncConcentrationBreaches(bytes32[] calldata borrowerIds, bytes32[] calldata stateIds) external;
/// @notice The largest `principal` that `checkConcentration` would admit right now for
/// (`classId`,`borrowerId`,`stateId`) — the binding minimum across the class,
/// borrower and state dimensions. Zero for an unknown or inactive class.
function concentrationHeadroom(uint256 classId, bytes32 borrowerId, bytes32 stateId)
external
view
returns (uint256);
}
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/interfaces/IGovernanceSchedule.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title IGovernanceSchedule — the live length of the protocol's governance path
/// @notice AUDIT FIX (R6-CF1). The three parameters that together determine how long it takes a
/// proposal to become an executed on-chain act: `votingDelay` + `votingPeriod` on the
/// governor, plus the timelock's `getMinDelay`.
/// @dev WHY THIS INTERFACE EXISTS, AND WHY THE VALUES ARE READ LIVE RATHER THAN COMPILED IN.
/// `CuratorModule`'s guardian pre-arm must outlast the full governance path, or the freeze it
/// buys lapses before governance can possibly ratify it and the protection is decorative.
/// All three parameters are GOVERNANCE-MUTABLE (`GovernorSettings.setVotingDelay` /
/// `setVotingPeriod`, `TimelockController.updateDelay`), so a hardcoded literal — or even the
/// `Config` launch constants alone — silently becomes wrong the day any one of them is
/// retuned. The `Config` sum is kept as a FLOOR; this interface supplies the live reading
/// that overrides it upwards.
///
/// Deliberately NOT the full `IGovernor`: this is a parameter source, and a narrow interface
/// is what lets a future governor implementation satisfy it without inheriting OZ's stack.
interface IGovernanceSchedule {
/// @notice ERC-6372 clock description. Only `"mode=timestamp"` is commensurable with
/// `block.timestamp`; a block-number clock reports voting windows in units that must
/// NOT be added to a timestamp, and callers must fall back to their own floor.
function CLOCK_MODE() external view returns (string memory);
/// @notice Delay between proposal submission and the start of voting, in clock units.
function votingDelay() external view returns (uint256);
/// @notice Length of the voting window, in clock units.
function votingPeriod() external view returns (uint256);
/// @notice The timelock that executes passed proposals.
function timelock() external view returns (address);
}
/// @title ITimelockSchedule — the executing timelock's minimum delay
interface ITimelockSchedule {
/// @notice Minimum seconds an operation must sit queued before it may execute.
function getMinDelay() external view returns (uint256);
}
src/interfaces/IPointsModule.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title IPointsModule
/// @notice Balance-change hooks consumed by the sUSDfr vault and the USDfr token (ADR-0016,
/// 2026-07-14 directive). Both are fail-open at the caller.
interface IPointsModule {
/// @notice Notifies the points ledger of an sUSDfr share balance change (vault-only).
function onSharesTransfer(address from, address to, uint256 amount) external;
/// @notice Notifies the points ledger of a USDfr balance change (USDfr-token-only).
/// USDfr holders accrue at a governance multiple of the sUSDfr rate, in lieu of yield.
function onUSDfrTransfer(address from, address to, uint256 amount) external;
/// @notice Notifies the points ledger of a curator's new posted first-loss for a class
/// (CuratorModule-only). First-loss capital accrues at the curator multiple (P-01).
/// @param newPosted The curator's live postedOf(classId, curator) after the change.
function onCuratorStakeChange(address curator, uint256 classId, uint256 newPosted) external;
/// @notice Notifies the points ledger that a class absorbed a loss (CuratorModule-only).
/// Curator positions in that class stop accruing at their cached balance until
/// reconciled, so impaired first-loss can't out-accrue live capital.
/// @dev LEGACY form, retained so an un-upgraded CuratorModule keeps recording the freeze.
/// It carries no dilution ratio, so the ledger distrusts every cached balance in the
/// class — conservative, never over-crediting. Prefer the three-argument form.
/// @notice Notifies the points ledger that a class absorbed a loss, with the pool balances
/// bracketing the absorption (CuratorModule-only). Equal balances are ignored because
/// a representation-only normalization is not an economic loss. For an economic loss,
/// the ratio lets the ledger write cached balances down without iterating curators
/// (H-03/M-4).
/// @param classId The collateral class that absorbed the loss.
/// @param poolBalanceBefore The class first-loss pool balance immediately before absorption.
/// @param poolBalanceAfter The class first-loss pool balance immediately after absorption.
function onCuratorLoss(uint256 classId, uint256 poolBalanceBefore, uint256 poolBalanceAfter) external;
}
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/interfaces/IsUSDfr.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
/// @title IsUSDfr
/// @notice The yield-bearing ERC-4626 vault over USDfr (ADR-0005). Yield accrues via the
/// assets/shares exchange rate; exits are routed through the epoch redemption
/// queue (ADR-0010) — the vault's instant withdraw/redeem paths are restricted
/// to the queue module.
interface IsUSDfr is IERC4626 {
/// @notice Settlement waits until servicing resolves all reversible past-due marks.
error SUSDfr_UnresolvedPastDue(uint256 exposure);
/// @notice Reversible risk blocking new withdrawals; quotes and existing cash claims remain readable.
function unresolvedPastDueExposure() external view returns (uint256);
/// @notice Caller is not a loss burner of a controller authorized to mint this asset.
error SUSDfr_InvalidLossProtectionSource(address source, address controller);
/// @notice A previously consumed lifetime capital record may never decrease.
error SUSDfr_LossProtectionCounterDecreased(address source, uint256 previous, uint256 current);
/// @notice Actual consumed protection was excluded from the global performance-fee basis.
event LossProtectionBasisCredited(address indexed source, uint256 capital, uint256 highWaterMark);
/// @notice Pulls the caller's cumulative consumed-protection record, crediting only new capital.
/// @dev Restricted to authenticated fee-accounting/loss actors; no amount is caller supplied.
function syncProtectedCapital(address controller) external;
/// @notice Emitted when the redemption queue address is set.
event RedemptionQueueUpdated(address indexed queue);
/// @notice Instant exit attempted by an account other than the redemption queue.
error SUSDfr_QueueOnly();
/// @notice Share movement involving a sanctioned (blocked) party.
error SUSDfr_TransferBlocked(address from, address to);
/// @notice A management-fee rate above the permanent v1 cap was requested.
error SUSDfr_ManagementFeeTooHigh(uint16 requestedBps);
/// @notice A performance-fee rate above the permanent v1 cap was requested.
error SUSDfr_PerformanceFeeTooHigh(uint16 requestedBps);
/// @notice A fee checkpoint was attempted during a transient share update or
/// while a cross-module fee-accounting operation was locked.
error SUSDfr_FeeAccrualReentrant();
/// @notice A two-phase fee-accounting operation was completed by the wrong caller
/// or with the wrong operation type.
error SUSDfr_InvalidFeeOperation(address caller, uint8 expectedKind, uint8 actualKind);
/// @notice Share supply changed during a fee-neutral marked-NAV operation.
error SUSDfr_FeeOperationSupplyChanged(uint256 expectedSupply, uint256 actualSupply);
/// @notice A replacement fee recipient was not marked as a protocol-exempt address.
error SUSDfr_FeeRecipientNotExempt(address recipient);
/// @notice A proposed impairment source has no code or cannot return a uint256 impairment.
error SUSDfr_InvalidImpairmentSource(address source);
/// @notice A source reported less performance-fee impairment than redemption impairment.
error SUSDfr_InvalidPerformanceFeeImpairment(uint256 pendingImpairment, uint256 performanceImpairment);
/// @notice Emergency clearing was requested while the current impairment source is valid.
error SUSDfr_ImpairmentSourceStillReadable(address source);
/// @notice Emergency clearing was requested when no impairment source is configured.
error SUSDfr_NoImpairmentSource();
/// @notice Too little gas was supplied to prove source failure and finish recovery safely.
error SUSDfr_InsufficientImpairmentRecoveryGas(uint256 available, uint256 required);
/// @notice Emitted when the (fail-open) points hook reverted on a share move (P-04 telemetry).
event PointsHookFailed(address indexed from, address indexed to, uint256 value);
/// @notice Protocol fee shares were minted for time-based management fees.
event ManagementFeeAccrued(uint256 elapsed, uint256 feeAssets, uint256 feeShares);
/// @notice Protocol fee shares were minted on marked NAV above the global high-water mark.
event PerformanceFeeAccrued(
uint256 oldHighWaterMark, uint256 newHighWaterMark, uint256 profitAssets, uint256 feeAssets, uint256 feeShares
);
/// @notice A fee-neutral flow adjusted the global high-water mark.
event HighWaterMarkAdjusted(uint256 oldHighWaterMark, uint256 newHighWaterMark);
/// @notice An authorized module checkpointed fees and locked a junior-capacity operation.
event FeeNeutralMarkedNavChangeStarted(address indexed module, uint256 supply);
/// @notice The authorized junior-capacity operation released its checkpoint lock.
event FeeNeutralMarkedNavChangeCompleted(address indexed module, uint256 supply);
/// @notice The WaterfallEngine locked fee checkpoints before delivering senior yield.
event YieldNotificationStarted(address indexed module);
/// @notice Governance cleared a fee-operation lock left behind by a faulty trusted module.
event FeeOperationEmergencyCleared(address indexed module, uint8 indexed operationKind);
/// @notice The queue prepared one settlement chunk against the full remaining settlement
/// outflow bound before taking any price quote.
/// @param maxAssets Maximum USDfr that the live settlement can still distribute.
/// @param projectedHeld Physical USDfr that would remain if that full bound left the vault.
/// @param instantlyRecognized Previously-unvested yield released before pricing.
event RedemptionPricingPrepared(uint256 maxAssets, uint256 projectedHeld, uint256 instantlyRecognized);
/// @notice Timelocked governance changed the prospective annual management-fee rate.
event ManagementFeeSet(uint16 oldFeeBps, uint16 newFeeBps);
/// @notice Timelocked governance changed the prospective global performance-fee rate.
event PerformanceFeeSet(uint16 oldFeeBps, uint16 newFeeBps);
/// @notice Timelocked governance changed the recipient of future vault fee shares.
event VaultFeeRecipientSet(address indexed oldRecipient, address indexed newRecipient);
/// @notice Timelocked governance cleared an unreadable impairment source without checkpointing it.
/// @dev `failureHash` commits to the failed selector and bounded return evidence, or
/// to the semantically invalid pair of impairment values.
event ImpairmentSourceEmergencyCleared(address indexed source, bytes32 failureHash);
/// @notice Current fee-net realized exchange rate: assets per one whole sUSDfr token.
/// @dev Simulates fee shares due at this timestamp even before a checkpoint transaction.
function currentExchangeRate() external view returns (uint256);
/// @notice Crystallizes management and global high-water-mark performance fees.
/// @dev Permissionless. Fee shares mint to `feeRecipient`; no backing assets leave.
/// @return managementShares Shares minted for the time-based management fee.
/// @return performanceShares Shares minted for profit above the high-water mark.
function accrueFees() external returns (uint256 managementShares, uint256 performanceShares);
/// @notice Prepares queue redemption pricing against the live settlement's full remaining
/// outflow bound, then checkpoints fees once against the prepared state.
/// @dev Queue-only. Using the settlement bound rather than the caller-selected request count
/// makes optional-stream recognition independent of keeper chunking (G4/M-2).
/// @param maxAssets Maximum USDfr the settlement can still distribute.
/// @return instantlyRecognized Previously-unvested yield released before pricing.
function prepareRedemptionPricing(uint256 maxAssets) external returns (uint256 instantlyRecognized);
/// @notice Checkpoints fees and locks checkpoints before an authorized junior-capacity change.
/// @dev Must be paired atomically with `endFeeNeutralMarkedNavChange` by the same module.
/// Junior-capacity effects are excluded by the impairment source's independent
/// performance-fee view; this function never infers a capital flow from a NAV re-read.
function beginFeeNeutralMarkedNavChange() external;
/// @notice Releases an authorized junior-capacity operation's checkpoint lock.
/// @dev The caller and share supply must match the opening snapshot.
function endFeeNeutralMarkedNavChange() external;
/// @notice Locks vault fee checkpoints before the WaterfallEngine delivers senior yield.
/// @dev Must be paired atomically with `notifyYield` by the same module.
function beginYieldNotification() external;
/// @notice Clears a fee-operation lock that survived a successful trusted-module call.
/// @dev Timelocked emergency recovery only. Correct module paths open and close their
/// lock atomically, so a persistent lock means the trusted caller is faulty.
function clearStaleFeeOperation() external;
/// @notice Current global performance-fee rate, in basis points of profit.
function performanceFeeBps() external view returns (uint16);
/// @notice Permanent v1 performance-fee ceiling, in basis points.
function maxPerformanceFeeBps() external pure returns (uint16);
/// @notice Current annualized management-fee rate, in basis points.
function managementFeeBps() external view returns (uint16);
/// @notice Permanent v1 management-fee ceiling, in basis points.
function maxManagementFeeBps() external pure returns (uint16);
/// @notice Time basis used to interpret the annual management-fee rate.
function managementFeeYear() external pure returns (uint64);
/// @notice Global post-fee high-water mark, in the same units as `feeExchangeRate`.
function highWaterMark() external view returns (uint256);
/// @notice Gross rate used for HWM accounting after fee-neutral junior-capital credit.
/// @dev Unlike `currentExchangeRate`, this does not simulate pending fee shares. It can be
/// below the redemption-NAV rate while junior capital protects a live impairment.
function feeExchangeRate() external view returns (uint256);
/// @notice Recipient of sUSDfr management/performance fee shares.
function feeRecipient() external view returns (address);
/// @notice Last timestamp through which the management fee was accrued.
function lastFeeAccrual() external view returns (uint64);
/// @notice Sets the prospective management fee. Timelocked governance only.
function setManagementFee(uint16 feeBps) external;
/// @notice Sets the prospective performance fee. Timelocked governance only.
function setPerformanceFee(uint16 feeBps) external;
/// @notice Changes the recipient of future vault fee shares. Timelocked governance only.
function setFeeRecipient(address recipient) external;
/// @notice Clears a configured impairment source only when a bounded read demonstrably fails.
/// @dev Timelocked governance recovery path. It deliberately cannot replace a readable source
/// or install a new source; normal changes must use the checkpointed setter. Any marked-NAV
/// lift is ratcheted fee-free, permanently waiving performance fees embedded in that lift.
function clearUnreadableImpairmentSource() external;
/// @notice Sets or clears the conservative marked-NAV impairment source.
/// @dev Timelocked governance only. A non-zero replacement must pass an ABI read before
/// the old valuation period is checkpointed and the replacement is stored.
function setImpairmentSource(address source) external;
/// @notice Current conservative marked-NAV impairment source, or zero when unwired.
function impairmentSource() external view returns (address);
/// @notice The redemption queue module (sole permitted caller of withdraw/redeem).
function redemptionQueue() external view returns (address);
/// @notice Sets the redemption queue. Only DEFAULT_ADMIN_ROLE (timelocked governance).
function setRedemptionQueue(address queue) external;
/// @notice Recognizes realized senior yield immediately or starts optional vesting (ADR-0023).
/// @dev Called by the WaterfallEngine right after it delivers `amount` USDfr into the
/// vault. Moves no value. With a zero vesting period, recognition and the resulting
/// performance-fee checkpoint complete in the caller's repayment transaction. A
/// non-zero governance setting defers recognition linearly as an optional
/// market-smoothing policy. Gated by CREDIT_ROLE.
/// @param amount The realized yield just delivered into the vault.
function notifyYield(uint256 amount) external;
/// @notice Realized senior yield not yet released into the exchange rate (ADR-0023).
function unvestedYield() external view returns (uint256);
/// @notice The asset base exits price against: realized assets LESS the
/// declared-but-unrealized senior impairment (ADR-0022 Option Y).
/// @dev Always `<= totalAssets()`, so redemption NAV <= deposit NAV.
function redemptionTotalAssets() external view returns (uint256);
/// @notice Shares that `assets` buys at the conservative redemption NAV, rounded DOWN.
/// @dev The floor-rounded counterpart to `previewWithdraw` (which rounds up). The queue caps
/// its settlement budget with this so `previewRedeem(result) <= assets` holds by
/// construction and settlement can never distribute above the budget (CLAUDE.md §1.3).
/// @param assets The budget, in USDfr.
/// @return The largest share count whose conservative redemption value does not exceed `assets`.
function convertToSharesAtRedemption(uint256 assets) external view 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;
}
src/libraries/PointsHookGas.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @notice A caller supplied too little gas for a token's configured points hook to complete
/// while retaining enough gas to complete the token epilogue safely.
error PointsHook_InsufficientGas(uint256 available, uint256 required);
/// @title PointsHookGas
/// @notice Shared gas policy for the USDfr and sUSDfr participation-points hooks.
/// @dev A healthy hook may complete at any gas budget above the epilogue reserve. An empty-data
/// failure below the classification threshold is treated as caller-controlled exhaustion
/// and rolls the token movement back. Once that threshold was actually offered, an ordinary
/// module failure remains fail-open and observable. Reserving gas explicitly avoids relying
/// on EIP-150's retained 1/64 to fund catch telemetry and, for sUSDfr, release the
/// share-update lock.
library PointsHookGas {
/// @dev This is deliberately not an up-front floor: a healthy hook measured at materially
/// less gas is allowed to succeed. Cold two-wallet tests cover 128 historical rate
/// epochs with narrow headroom. Longer stale histories may need reconciliation.
uint256 internal constant FAILURE_CLASSIFICATION_GAS = 2_000_000;
/// @dev Bounds an optional failure so two exhausted hooks fit the queue's 8M budget.
/// This cap is independent of the 2M classifier; it does not guarantee arbitrary
/// historical catch-up. Permissionless checkpoint/reconcile remains available.
uint256 internal constant MAX_HOOK_GAS = 2_500_000;
/// @dev Retained by the token rather than offered to the hook, so an exhausted hook can be
/// classified and the catch path can emit telemetry or roll the movement back.
uint256 internal constant POST_HOOK_RESERVE = 30_000;
/// @dev Covers fixed-size ABI preparation and the cold CALL charge before EIP-150 applies.
/// Both callers encode exactly three static words; no dynamic returndata is copied.
uint256 internal constant CALL_PREPARATION_GAS = 5_000;
/// @notice Offers a bounded allowance while retaining the token's epilogue.
function hookGasLimit() internal view returns (uint256) {
return hookGasLimit(0);
}
/// @notice Also retains the next mandatory financial leg's allowance when one is pending.
/// @dev The requested allowance never exceeds the conservative EIP-150 forwarding bound.
/// In particular, the classifier cannot mistake gas retained by the caller for gas
/// supplied to the hook. Capping each optional call also leaves later hooks usable.
function hookGasLimit(uint256 followingReserve) internal view returns (uint256 hookGas) {
uint256 available = gasleft();
uint256 retained = POST_HOOK_RESERVE + followingReserve + CALL_PREPARATION_GAS;
if (available <= retained) {
revert PointsHook_InsufficientGas(available, retained + 1);
}
unchecked {
uint256 afterCallCost = available - CALL_PREPARATION_GAS;
uint256 eip150 = afterCallCost - afterCallCost / 64;
hookGas = available - retained;
if (hookGas > eip150) hookGas = eip150;
if (hookGas > MAX_HOOK_GAS) hookGas = MAX_HOOK_GAS;
}
}
/// @notice Rolls back an ambiguous empty-data failure below the classification budget.
/// @dev Callers pass only the returndata size, avoiding an unbounded returndata allocation in
/// the token catch path. Non-empty failures and sufficiently funded empty failures remain
/// fail-open so a broken optional module cannot freeze financial movements indefinitely.
function requireSafeFailure(uint256 hookGas, uint256 returnSize) internal pure {
if (returnSize == 0 && hookGas < FAILURE_CLASSIFICATION_GAS) {
revert PointsHook_InsufficientGas(hookGas, FAILURE_CLASSIFICATION_GAS);
}
}
}
src/libraries/Roles.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
// GENERATED by tools/generate-privilege-topology.mjs from config/privilege-topology.json.
// Do not edit this file directly; the compiler-AST topology gate rejects drift.
/// @title Roles
/// @notice Canonical role identifiers for the protocol's access-control matrix.
/// @dev DEFAULT_ADMIN_ROLE is inherited from AccessControl and represented by bytes32(0).
library Roles {
// NOTE: A QUEUE_ROLE existed through Phase H but was never consumed. The vault gates its exit by the configured redemption-queue address, which is the stronger check; it was removed at Phase I cleanup.
/// @notice May authorize UUPS upgrades. Held only by the governance timelock.
bytes32 internal constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
/// @notice Emergency pause/unpause on value-moving paths. Cannot upgrade or move value.
bytes32 internal constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE");
/// @notice May mint USDfr. Held only by the MintRedeemController.
bytes32 internal constant MINTER_ROLE = keccak256("MINTER_ROLE");
/// @notice Reserve custody operations (deposit/release). Held only by the MintRedeemController.
bytes32 internal constant CONTROLLER_ROLE = keccak256("CONTROLLER_ROLE");
/// @notice Principal deployment, atomic payment receipt, and writedown. Held by credit modules.
bytes32 internal constant CREDIT_ROLE = keccak256("CREDIT_ROLE");
/// @notice May burn USDfr to realize an authenticated loss. Held only by DefaultManager and ReserveManager.
/// @dev AUDIT R16-M1: burnLoss is deliberately split from CREDIT_ROLE so the repayment engine cannot compose mint and burn authority.
bytes32 internal constant LOSS_BURNER_ROLE = keccak256("LOSS_BURNER_ROLE");
/// @notice May bracket a junior-capacity change so the vault preserves its asset-denominated performance-fee hurdle. Held only by the curator, sGROVE, and DefaultManager modules.
bytes32 internal constant FEE_ACCOUNTING_ROLE = keccak256("FEE_ACCOUNTING_ROLE");
/// @notice Manages KYC allowlist and jurisdiction blocklist entries.
bytes32 internal constant COMPLIANCE_ADMIN_ROLE = keccak256("COMPLIANCE_ADMIN_ROLE");
/// @notice Reserve configuration and conservative USDC custody write-downs.
bytes32 internal constant RESERVE_ADMIN_ROLE = keccak256("RESERVE_ADMIN_ROLE");
/// @notice May originate facilities (Phase D).
bytes32 internal constant ORIGINATOR_ROLE = keccak256("ORIGINATOR_ROLE");
/// @notice Authorized attesters (Phase G, ADR-0007).
bytes32 internal constant ATTESTER_ROLE = keccak256("ATTESTER_ROLE");
/// @notice Servicing operations: facility funding, repayment distribution, default declaration, and loss realization. Held by Forest Road servicing keys until Phase G binds these paths to attested facts; the role then gates who may execute an already-attested action, not what is true.
bytes32 internal constant SERVICER_ROLE = keccak256("SERVICER_ROLE");
/// @notice Drives RedemptionQueue.closeEpoch. Operational, not governance or upgrade authority: it initiates a financially effective settlement and controls when its budget is sampled, but cannot choose recipients, reorder FIFO, set parameters, or exceed the contract-enforced budget and pricing rules.
/// @dev AUDIT FIX D7-01: closeEpoch samples the epoch liquidity budget as a spot read and the fill loop re-reads it every chunk. While permissionless, a caller could hold flash liquidity across both reads; measured excess budget was $1.62M from Morpho alone and $4.31M from stacked Aave and Morpho borrowing. A flash loan cannot span two transactions, so the keeper gate closes the vector at its root. This supersedes ADR-0018 section 2's permissionless-settlement design. Grant the role to at least two holders: a hot keeper and a manual ops-multisig backstop. A total keeper outage is bounded only by governance regranting the role. A permissionless grace fallback was rejected because it would restore the flash vector whenever the keeper missed the window.
bytes32 internal constant SETTLEMENT_KEEPER_ROLE = keccak256("SETTLEMENT_KEEPER_ROLE");
}
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.