Verified contractExactBUSL-1.1
ControllerAccrualLib
Address0xbd3ad32762f3fbcac3b5186c8355a3749fb4126f
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.30
- Same code
Only this contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 100 runs
- EVM version
- cancun
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,486,023
- Creation transaction
- 0xf1b13e0b71…dfb69bc13f
34 files
- src/libraries/ControllerAccrualLib.solmain10.53 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/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/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/MintRedeemController.sol143.75 KB
- src/interfaces/IAccrualLifecycle.sol6.67 KB
- src/interfaces/IComplianceRegistry.sol2.52 KB
- src/interfaces/IContinuousAccrual.sol4.69 KB
- src/interfaces/IMintRedeemController.sol42.91 KB
- src/interfaces/IReserveManager.sol31.28 KB
- src/interfaces/ISeniorExitDrawSource.sol2.15 KB
- src/interfaces/IUSDfr.sol3.2 KB
- src/libraries/Roles.sol4.2 KB
src/libraries/ControllerAccrualLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
import {MintRedeemController} from "../MintRedeemController.sol";
import {IMintRedeemController} from "../interfaces/IMintRedeemController.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IContinuousAccrual, IAccrualToken} from "../interfaces/IContinuousAccrual.sol";
import {IAccrualRounding} from "../interfaces/IAccrualLifecycle.sol";
/// @title ControllerAccrualLib
/// @notice Linked controller helpers for effective supply and exact accrual delivery.
/// @dev Executes in the controller's context. Its host owns governance and reentrancy guards.
library ControllerAccrualLib {
/// @dev One pre-issuance snapshot, or the same caller's paired pre-backing snapshot.
struct YieldBaseline {
uint256 supply;
uint256 backing;
uint256 recognized;
bool paired;
uint256 retention;
}
/// @notice Issues the complete yield increase before applying the original backing and retention checks.
/// @dev The host enforces CREDIT_ROLE, pause and nonReentrant. Splitting never rounds either
/// recipient to a reserve-token unit: the already recognized total is split in USDfr wei.
/// A failed second mint or closing check restores both mints and the paired baseline.
function mintYield(
MintRedeemController.ControllerStorage storage $,
address senior,
uint256 total,
address feeRecipient,
uint256 fee
) public {
if (total == 0) revert IMintRedeemController.Controller_ZeroAmount();
if (fee > total) revert IMintRedeemController.Controller_InvalidYieldSplit(total, fee);
if (address($.accrual) != address(0)) $.accrual.requireAccrualFresh();
uint256 toSenior = total - fee;
if (toSenior != 0 && !$.yieldSink[senior]) revert IMintRedeemController.Controller_NotYieldSink(senior);
if (fee != 0 && !$.yieldSink[feeRecipient]) revert IMintRedeemController.Controller_NotYieldSink(feeRecipient);
YieldBaseline memory before_ = _yieldBaseline($);
if (fee != 0) $.usdfr.mint(feeRecipient, fee);
if (toSenior != 0) $.usdfr.mint(senior, toSenior);
_verifyYield($, before_);
if (fee != 0) emit IMintRedeemController.YieldMinted(feeRecipient, fee);
if (toSenior != 0) emit IMintRedeemController.YieldMinted(senior, toSenior);
}
function _yieldSupply(MintRedeemController.ControllerStorage storage $) private view returns (uint256) {
return address($.accrual) == address(0) ? $.usdfr.totalSupply() : supply(address($.accrual), address($.usdfr));
}
function _yieldBaseline(MintRedeemController.ControllerStorage storage $)
private
returns (YieldBaseline memory before_)
{
before_.paired = $.pairedYieldCaller == msg.sender;
if (before_.paired) {
before_.supply = $.pairedSupplyBefore;
before_.backing = $.pairedBackingBefore;
before_.recognized = $.pairedRecognizedBefore;
before_.retention = $.pairedRetentionBefore;
$.pairedYieldCaller = address(0);
$.pairedSupplyBefore = 0;
$.pairedBackingBefore = 0;
$.pairedRecognizedBefore = 0;
$.pairedRetentionBefore = 0;
} else {
before_.supply = _yieldSupply($);
before_.backing = $.reserves.totalBackingValue();
before_.recognized = $.reserves.recognizedBackingValue();
}
}
/// @dev Preserves both non-worsening deficit checks and the existing retention rule.
function _verifyYield(MintRedeemController.ControllerStorage storage $, YieldBaseline memory before_)
private
view
{
uint256 supplyAfter = _yieldSupply($);
uint256 backingAfter = $.reserves.totalBackingValue();
uint256 deficitBefore = before_.supply > before_.backing ? before_.supply - before_.backing : 0;
uint256 deficitAfter = supplyAfter > backingAfter ? supplyAfter - backingAfter : 0;
if (deficitAfter > deficitBefore) {
if (deficitBefore == 0) {
revert IMintRedeemController.Controller_BackingInvariantViolated(supplyAfter, backingAfter);
}
revert IMintRedeemController.Controller_DeficitWorsened(deficitBefore, deficitAfter);
}
uint256 recognizedAfter = $.reserves.recognizedBackingValue();
deficitBefore = before_.supply > before_.recognized ? before_.supply - before_.recognized : 0;
deficitAfter = supplyAfter > recognizedAfter ? supplyAfter - recognizedAfter : 0;
if (deficitAfter > deficitBefore) {
revert IMintRedeemController.Controller_RecognizedDeficitWorsened(deficitBefore, deficitAfter);
}
uint256 retention = $.subParShortfall + $.reserves.exitPrepaidAbsorption();
if (before_.paired && retention != before_.retention) {
revert IMintRedeemController.Controller_PairedRetentionChanged(before_.retention, retention);
}
if (retention != 0) {
uint256 surplus = recognizedAfter > supplyAfter ? recognizedAfter - supplyAfter : 0;
if (before_.paired) {
uint256 previous = before_.recognized > before_.supply ? before_.recognized - before_.supply : 0;
if (surplus != previous) {
revert IMintRedeemController.Controller_SeniorRetentionBreached(previous, surplus);
}
} else if (surplus < retention) {
revert IMintRedeemController.Controller_SeniorRetentionBreached(retention, surplus);
}
}
}
/// @notice The reserve, token and controller must identify this same instance.
error ControllerAccrual_WrongModules();
/// @notice Only the bound reserve can continue its current delivery operation.
error ControllerAccrual_InvalidDelivery();
/// @notice Existing yield destination authorization also applies to accrued claims.
error ControllerAccrual_UnauthorizedRecipient(address recipient);
/// @notice The token did not physically issue exactly the authorized selected claims.
error ControllerAccrual_SupplyDeltaMismatch(uint256 expected, uint256 actual);
/// @notice Validates the configured reserve before the controller opts into its accounting.
function validate(address reserve, address token) public view {
if (reserve.code.length == 0) revert ControllerAccrual_WrongModules();
IContinuousAccrual.Modules memory m = IContinuousAccrual(reserve).accrualModules();
if (
m.controller != address(this) || m.token != token || m.vault.code.length == 0
|| IAccrualToken(token).accrualReserve() != reserve
) {
revert ControllerAccrual_WrongModules();
}
}
/// @notice Economic supply includes all earned claims awaiting physical minting.
/// @dev The operation snapshot hides the temporary debit-before-mint window from callbacks.
function supply(address reserve, address token) public view returns (uint256) {
IContinuousAccrual source = IContinuousAccrual(reserve);
IContinuousAccrual.Delivery memory d = source.accrualDelivery();
if (d.active) return d.effectiveSupply;
return IERC20(token).totalSupply() + source.accrualSnapshot().unissued;
}
/// @notice Whether a current price-sensitive operation may start.
function available(address reserve) public view returns (bool) {
IContinuousAccrual source = IContinuousAccrual(reserve);
if (!source.accrualSnapshot().fresh || source.accrualDelivery().active) return false;
// Freshness is necessary but does not imply admission: the host can have another
// conflicting operation in progress without an active delivery permit.
try source.requireAccrualFresh() {
return true;
} catch {
return false;
}
}
/// @notice Preserves normal loss admission, or consumes the reserve's exact rounding-burn continuation.
/// @dev The controller host still enforces LOSS_BURNER_ROLE, the authorized endpoint and its
/// nonReentrant guard. The reserve accepts only itself as caller and one armed amount/sink.
function authorizeLossBurn(address reserve, address from, uint256 amount) public {
if (reserve == address(0)) return;
if (!IAccrualRounding(reserve).consumeAccrualLossBurn(msg.sender, from, amount)) {
IContinuousAccrual(reserve).requireAccrualFresh();
}
}
/// @notice Relays only the current reserve-owned, exactly sized permit to its token.
/// @dev Pausing expansion does not prevent conversion of an existing economic liability.
/// The controller proves the raw supply delta; the reserve independently proves its
/// accounting closure and recipient balance deltas before completing delivery.
function deliver(address reserve, address token, mapping(address => bool) storage sinks, uint256 nonce) public {
if (reserve == address(0) || msg.sender != reserve) revert ControllerAccrual_InvalidDelivery();
IContinuousAccrual source = IContinuousAccrual(reserve);
IContinuousAccrual.Delivery memory d = source.accrualDelivery();
if (
!d.active || d.nonce != nonce || d.controller != address(this) || d.accruedThrough != block.timestamp
|| d.legs == 0 || d.legs > 3 || (d.senior == 0 && d.fee == 0) || ((d.legs & 1) == 0 && d.senior != 0)
|| ((d.legs & 2) == 0 && d.fee != 0) || !d.pricing.materializationAllowed
|| IAccrualToken(token).accrualReserve() != reserve
) revert ControllerAccrual_InvalidDelivery();
if (d.senior != 0 && !sinks[d.vault]) revert ControllerAccrual_UnauthorizedRecipient(d.vault);
if (d.fee != 0 && !sinks[d.feeRecipient]) revert ControllerAccrual_UnauthorizedRecipient(d.feeRecipient);
if (d.senior > type(uint256).max - d.fee) revert ControllerAccrual_InvalidDelivery();
uint256 expected = d.senior + d.fee;
uint256 beforeSupply = IERC20(token).totalSupply();
IAccrualToken(token).mintAccrued(nonce);
uint256 afterSupply = IERC20(token).totalSupply();
uint256 actual = afterSupply < beforeSupply ? 0 : afterSupply - beforeSupply;
if (actual != expected) revert ControllerAccrual_SupplyDeltaMismatch(expected, actual);
}
}
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/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/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/MintRedeemController.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 {IComplianceRegistry} from "./interfaces/IComplianceRegistry.sol";
import {IMintRedeemController, IPausableModule} from "./interfaces/IMintRedeemController.sol";
import {IReserveManager} from "./interfaces/IReserveManager.sol";
import {ISeniorExitDrawSource} from "./interfaces/ISeniorExitDrawSource.sol";
import {IUSDfr} from "./interfaces/IUSDfr.sol";
import {IContinuousAccrual} from "./interfaces/IContinuousAccrual.sol";
import {ControllerAccrualLib} from "./libraries/ControllerAccrualLib.sol";
import {Roles} from "./libraries/Roles.sol";
/// @title MintRedeemController
/// @notice The only mint/burn path for USDfr, and the enforcement point of the backing
/// invariant (ADR-0012). Mint/redeem is KYC-gated (ADR-0011); yield-mint and
/// loss-burn are credit-layer paths (Phase E/G).
///
/// @dev THE SOLVENCY MODEL, IN ONE PLACE (audit round R16 — findings M3/M4/M5).
/// Before this round the contract had exactly ONE solvency predicate: the absolute
/// inequality `totalSupply <= backingValue`, asserted identically after mint, redeem,
/// mintYield and burnLoss. An absolute inequality has only two states, and both of them
/// were wrong once a loss was recognised:
/// - PRETEND. Nothing had recognised the loss yet, so the predicate reported TRUE and the
/// protocol went on issuing and honouring par claims against a hole (R4-01, G3).
/// - FREEZE. Once the loss WAS recognised, the predicate reported FALSE and stayed false,
/// and because every supply-affecting path asserted it, EVERY path reverted at once:
/// `mint`, `redeem`, `mintYield` and `burnLoss`, taking `WaterfallEngine.fund` and
/// `WaterfallEngine.distribute` down with them. A single G3 conservative mark — an
/// ordinary, expected credit event — therefore bricked the whole protocol with no
/// protocol-native cure (M5). Worse, `burnLoss` is the cascade's OWN instrument for
/// absorbing that loss, so the freeze disabled the only mechanism that could have
/// ended it.
///
/// THE REPLACEMENT IS ONE PREDICATE, NOT FOUR. Every supply-affecting path now asserts
/// the same rule, `_assertDeficitNotWorsened`: an operation may not INCREASE
/// `deficit = max(0, totalSupply - backingValue)`. That rule is strictly stronger than the
/// old one where the old one was meaningful and strictly weaker only where the old one was
/// merely punitive:
/// - while the protocol is whole (`deficit == 0`) it reduces EXACTLY to ADR-0012's
/// `totalSupply <= backingValue`, and still reverts with
/// `Controller_BackingInvariantViolated`;
/// - while the protocol is short it permits precisely the operations that repair or
/// preserve holders' position, and refuses the ones that dilute it.
/// With one rule there is no longer an "inconsistent predicate" question to get wrong (M4):
/// `mint`, `redeem` and `mintYield` all assert it, and `burnLoss` is the one path that
/// cannot violate it in any reachable state (see its NatSpec — that is stated as a proof,
/// not asserted as an unfalsifiable guard).
///
/// SUB-PAR REDEMPTION IS THE POINT (M3, AS AMENDED BY R17 — READ THE WHOLE PARAGRAPH; AN
/// EARLIER REVISION OF IT CONTRADICTED THE CODE AND THAT WAS ITSELF A FINDING). Freezing
/// redemption was justified on the ground that par exits out of a short pool are a run. That
/// is true of PAR exits and false of exits generally. THE TWO-ARGUMENT FORM
/// `redeem(uint256,uint256)` pays the coverage ratio: at `backing/supply == 0.97` a holder
/// who passes a floor of 0.97 or lower gets 97 cents, and the ratio left behind for everyone
/// who did not redeem is unchanged to the wei-rounding, which always favours the holders who
/// stayed. THE ONE-ARGUMENT FORM `redeem(uint256)` NEVER PAYS 97 CENTS: R17 gave it the PAR
/// FLOOR, so it either settles at PAR or reverts `Controller_SlippageExceeded` — it never
/// haircuts a caller who did not ask to be haircut (see `redeem(uint256)`).
///
/// CORRECTED (SWEEP-1 MRC-F2, 2026-08-08) — THIS PARAGRAPH SAID THE ONE-ARGUMENT FORM
/// "REVERTS" IN THE SHORT STATE, FULL STOP. THAT IS NO LONGER TRUE AND HAS NOT BEEN SINCE
/// ADR-0034 Y-bis. `_drawJuniorForExit` draws curator first-loss and the sGROVE backstop
/// forward IN THE SAME TRANSACTION to fund the cascade-ordered price, so while junior capital
/// stands the one-argument form can and does SETTLE AT PAR out of that capital; it reverts
/// only once the draw cannot reach par. MEASURED: with a gross quote of 185,928.705440 USDC
/// the one-argument form settled 200,000.000000. The correction matters because this very
/// paragraph carries the warning that "AN EARLIER REVISION OF IT CONTRADICTED THE CODE AND
/// THAT WAS ITSELF A FINDING". So the protocol can say "we
/// are 3% short, here is 97 cents" — but only to a holder who has elected that price.
/// `previewRedeem` publishes the quote so the number is knowable before signing, and the
/// number it returns is what should be passed back as `minUsdcOut`.
///
/// MINT STAYS CLOSED WHILE SHORT. It is not symmetric with redeem and must not be made so:
/// redeeming at the ratio is the holder's own money at an honest price, whereas minting at
/// par into a short book sells a NEW holder a claim worth less than the dollar they paid,
/// and minting at the ratio would let an insolvent protocol keep issuing. Closed is the
/// only honest answer, and it is the R4-01 finding restated.
///
/// @dev WHAT AUDIT ROUND R17 CHANGED, AND WHY (read this next). R16 made the exit price a live
/// function of state and published a view for it. The adversarial round that followed found
/// that the two halves of that change had not been finished:
///
/// (1) TWO BASES, ONE OF THEM FALSIFIABLE. `mintableHeadroom()` and `previewRedeem` were
/// measured on the RECORDED ledger, which an unreconciled custody shortfall has already
/// falsified — the exact R4-01 condition. `WaterfallEngine._routeInterest` sizes yield
/// off `mintableHeadroom()`, so under a custody hole the whole interest leg was minted
/// out as yield (protocol fee taken on the gross) while `mint` and `redeem` were frozen
/// and the hole was not repaired by a wei. Both views are now RECOGNITION-AWARE, and
/// `mintYield` asserts the non-worsening rule on BOTH bases. See `mintableHeadroom`.
///
/// (2) A VARIABLE PRICE WITH NO FLOOR. `redeem(uint256)` was written when the price was the
/// constant 1:1 and needed no `minUsdcOut`. Once the price moved, the one-argument form
/// silently accepted whatever the ratio happened to be at inclusion — and several
/// NON-timelocked paths (`recordPrincipalWritedown`, `reconcileIdleUSDC`) lower backing
/// in the same block. There is now `redeem(uint256,uint256)`, and the ONE-ARGUMENT FORM
/// DEFAULTS TO THE PAR FLOOR: it settles at par or reverts. A sub-par exit is now an
/// EXPLICIT, informed election by the holder, never a silent haircut.
///
/// (3) THE HAIRCUT WAS BEING RECYCLED AS JUNIOR YIELD. `recognizePrincipalImpairment` is a
/// REVERSIBLE governance valuation act (`releasePrincipalImpairment` exists precisely so
/// governance is willing to mark conservatively). A holder who exited against that mark
/// crystallised a permanent loss; when the mark was later released the recovered value
/// reappeared as `mintableHeadroom()` and was minted to the `sUSDfr` vault as yield. The
/// senior's haircut became someone else's income. `seniorSubParShortfall()` now records
/// the cumulative crystallised haircut and `mintableHeadroom()` nets it out, so recovered
/// value stays in the pool as coverage for the holders who are still in it instead of
/// being distributed. This is a MITIGATION, not a full answer — see that function's
/// NatSpec and `redeem`'s "WHAT THIS DOES NOT PROMISE" section for the part that is a
/// Forest Road decision, deliberately NOT taken unilaterally here (CLAUDE.md §0.5/§0.7).
///
/// (4) ONE LEG OF THE R16-L2 MEASUREMENT WAS MISSING. `mint` measured the reserve's own
/// balance across `depositUSDC`; `redeem` took the reserve's word for `releaseUSDC` — on
/// the leg where the holder's USDfr is ALREADY BURNED. `redeem` now measures the
/// redeemer's own balance across the release. See `Controller_RedemptionNotSettled`.
///
/// @dev WHAT AUDIT ROUND R18 CHANGED (the adversarial round that attacked R17). R17's mitigations
/// were sound on the paths they were written for and wrong on the adjacent ones. In order of
/// severity:
///
/// (A) THE SENIOR RETENTION FROZE ORIGINATION, PERMANENTLY. `Controller_SeniorRetentionBreached`
/// is an ABSOLUTE level check, and `WaterfallEngine.fund`'s origination-fee mint was the
/// one `mintYield` caller not sized off `mintableHeadroom()`. So a single crystallised
/// haircut refused `fund` outright — including on a book the protocol publishes as WHOLE
/// or OVER-backed — and the only cure the retention's own NatSpec named (withheld
/// interest) requires a funded facility, which requires the `fund` the retention had just
/// closed. That is finding M5 ("permanently inert, no protocol-native cure") restored on
/// the origination axis. R18 CLAMPS `fund`'s fee to `mintableHeadroom()` exactly the way
/// `_routeInterest` already clamps interest: the undistributable part is WITHHELD as
/// unencumbered backing (which is what rebuilds the surplus the retention wants) and the
/// facility funds. The retention is unchanged and still enforced here; it can no longer
/// brick the path that cures it. See `mintYield` and `seniorSubParShortfall`.
///
/// (B) THE D3 PAUSE FIX WAS HALF APPLIED. `mintableHeadroom()` read only THIS contract's
/// `paused()`. The same guardian key holds `GUARDIAN_ROLE` on `USDfr`, whose `_update`
/// refuses every mint while the token is paused, so one un-timelocked transaction still
/// reverted every interest-bearing `WaterfallEngine.distribute` — the exact harm the
/// clamp was built to prevent, through the pause the clamp could not see.
/// `mintableHeadroom()` now reads BOTH pauses. See `mintableHeadroom` and `pause`.
///
/// (C) EIP-7702 DEFEATED `setLossSource`'s CODE CHECK. Since Pectra an ordinary key-controlled
/// EOA that has signed a delegation carries a 23-byte `0xef0100`-prefixed code field, so
/// `EXTCODESIZE` returns 23 and R17's "no user wallet is seizable" claim was false for
/// precisely the wallets most users now hold. See `setLossSource`.
///
/// (D) THE FAIL-OPEN POINTS HOOK BECAME A REDEMPTION KILL SWITCH. `_redeem` opened its
/// outflow measurement window BEFORE `usdfr.burn`, and `USDfr._update` fires the
/// participation-points hook inside that burn. One wei of USDC moved to the redeemer by
/// that hook broke the settlement equality and reverted the redemption — from outside the
/// token's `try/catch`, so the token's protocol-wide "a points-module failure must never
/// block a transfer, mint or burn" rule held for transfers and not for redemptions. The
/// window now contains `releaseUSDC` and nothing else. See `_redeem`.
///
/// (E) THE VIEWS PUBLISHED THE OPPOSITE OF THE TRUTH MID-TRANSITION. `_redeem` burns before it
/// releases and `DefaultManager.realizeLoss` burns before it writes backing down, so an
/// observer that receives control inside a USDfr balance change (the points hook) read
/// `mintableHeadroom()` as the whole realised loss, `backingInvariantHolds()` as TRUE on a
/// short book and `previewRedeem` as PAR. The composite views now REVERT while this
/// contract's reentrancy guard is entered rather than answer a number that is false. See
/// `Controller_ViewUnavailableMidTransition`.
///
/// (F) `mint` MEASURED CUSTODY AND THE REPORTED CREDIT, NEVER RECOGNITION. A reserve that took
/// the cash, reported the right credit and never booked it as backing was caught only for
/// the part of the gap EXCEEDING the standing surplus, because the only thing covering
/// recognition was the NON-WORSENING rule. `mint` now measures the backing delta directly.
/// See `Controller_DepositNotRecognized`.
///
/// (G) `previewRedeem` QUOTED A SETTLEABLE PRICE FOR A CALL THAT CANNOT EXECUTE. It sits
/// outside `_requireCustodiedReserve` (correctly — it is permissionless), so under an
/// unreconciled custody shortfall it published an honest-looking quote for a `redeem` that
/// reverts. It now answers `(0, 0)`, which its documented contract already means
/// "nothing is payable". See `previewRedeem`.
///
/// (H) ADR-0034 IS ACCEPTED AND IS IMPLEMENTED HERE (CORRECTED, SWEEP-1 MRC-F2, 2026-08-08).
/// THIS PARAGRAPH USED TO READ "IS ACCEPTED AND IS NOT IMPLEMENTED HERE", and it was
/// flatly contradicted 1,300 lines below by `_quoteRedeem`'s own "ADR-0034 Y-bis IS
/// IMPLEMENTED, and `drawn` is what implements it", and by `_drawJuniorForExit` in this
/// same file. The history it describes is accurate and worth keeping: R16/R17 priced the
/// sub-par exit off the GROSS book mark, netting nothing against curator first-loss or the
/// sGROVE backstop, so a senior holder could be haircut while junior capital standing
/// behind them was intact; R16/R17 NatSpec called that an OPEN Forest Road question,
/// "raised, not taken"; ADR-0034 (Accepted, 2026-08-07) took it against the shipped
/// behaviour, and R18 corrected the comments. WHAT CHANGED AFTERWARDS: ADR-0034 Y-bis
/// (Forest Road, 2026-08-08) decided DRAW — junior capital is moved at the moment of the
/// senior exit, in the same transaction, so cascade order is enforced AT SETTLEMENT. That
/// is implemented, in `_drawJuniorForExit` and `_quoteRedeem`. Read those two for the
/// mechanism, and `DefaultManager.drawForSeniorExit` for what the draw may and may not do.
contract MintRedeemController is
Initializable,
AccessControlUpgradeable,
PausableUpgradeable,
ReentrancyGuardUpgradeable,
UUPSUpgradeable,
IMintRedeemController
{
using SafeERC20 for IERC20;
/// @custom:storage-location erc7201:forestroad.storage.MintRedeemController
/// @dev Fields are APPEND-ONLY (ERC-7201 namespaced struct) for upgrade safety. The two
/// endpoint maps were appended in audit round R16 (finding M1) — see `setYieldSink`
/// and `setLossSource`; `subParShortfall` was appended in R17 — see
/// `seniorSubParShortfall`. Verified with `tools/check-storage-layout.mjs` and
/// `tools/check-compiled-storage-layout.mjs`.
struct ControllerStorage {
IUSDfr usdfr;
IComplianceRegistry compliance;
IReserveManager reserves;
// ── append-only (upgrade safety) ──────────────────────────────────
/// @dev AUDIT FIX (R16-M1). Addresses `mintYield` may credit.
mapping(address account => bool) yieldSink;
/// @dev AUDIT FIX (R16-M1/M2). Addresses `burnLoss` may burn from.
mapping(address account => bool) lossSource;
/// @dev AUDIT FIX (R17). Cumulative value crystallised out of the senior layer by sub-par
/// exits, in 18-decimal USD. Monotonically non-decreasing. See
/// `seniorSubParShortfall`.
uint256 subParShortfall;
// ── PAIRED-YIELD BASELINE (2026-09-09) ───────────────────────────
/// @dev The CREDIT_ROLE caller that opened a paired-yield operation, or zero.
///
/// THIS IS NOT A SAME-TRANSACTION LOCK, and an earlier version of this note wrongly
/// called it one. Nothing in the EVM clears persistent storage at transaction end, so a
/// baseline opened and not consumed OUTLIVES its transaction, and because the deficit is
/// not monotone a baseline taken while a mark stood is a strictly LOOSER baseline for a
/// later mint. An adversarial review demonstrated one surviving 5,000 blocks and 30 days.
///
/// WHAT MAKES IT SAFE TODAY is the wiring, not the storage: `WaterfallEngine` is the
/// only CREDIT_ROLE holder on this contract, `capitalizePik` is the only opener, and it
/// contains no try/catch and reaches `mintYield` unconditionally, so no baseline can
/// survive its transaction. That is an argument about the CALLER, so it must be
/// re-made if CREDIT_ROLE is ever granted to anything else.
///
/// AND NOTHING ENFORCES EXCLUSIVITY. An earlier version of this note said
/// "`Validate.s.sol` asserts the holder set", which is not true and cannot be: no
/// contract in `src/` inherits `AccessControlEnumerable`, so role membership is not
/// enumerable on chain at all. `Validate.s.sol` asserts one positive (the engine holds
/// it) and three named negatives. A single `grantRole` to a fourth address would
/// restore the hazard and no gate would notice. EIP-1153 transient storage is the
/// structural answer and is the right fix the day solc's 2394 composability warning
/// can be triaged without blanket-suppressing it for every future `tstore`; suppressing
/// it now would stop `deny_warnings` catching any future misuse.
address pairedYieldCaller;
/// @dev Supply, recorded backing and recognised backing as at the START of the paired
/// operation, BEFORE the caller moved backing.
uint256 pairedSupplyBefore;
uint256 pairedBackingBefore;
uint256 pairedRecognizedBefore;
/// @dev Explicit, one-time opt-in to the bound reserve's continuous accounting.
IContinuousAccrual accrual;
/// @dev Retention requirement when the current paired operation opened; append-only.
uint256 pairedRetentionBefore;
}
/// @notice Continuous accounting can be bound only once.
error Controller_AccrualAlreadyBound();
/// @notice Delivery cannot overlap a legacy paired-yield operation.
error Controller_AccrualDuringPairedYield();
/// @notice This controller has opted into its configured reserve's accrual accounting.
event ContinuousAccrualBound(address indexed reserve);
/// @notice A reserve-owned delivery permit was relayed to USDfr.
event AccruedDeliveryRelayed(uint256 indexed nonce);
// keccak256(abi.encode(uint256(keccak256("forestroad.storage.MintRedeemController")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant CONTROLLER_STORAGE_LOCATION =
0x78d32d002402115460f3fdc161605476f91264ca4d3e131f8b3d65ead1f69100;
/// @dev USDfr is 18-decimal; canonical USDC is 6-decimal. One whole USDC unit is `SCALE`
/// wei of USDfr.
uint256 private constant SCALE = 1e12;
error Controller_ZeroAddress();
/// @notice A module handed to `initialize` is not a contract, or does not answer its interface.
/// @dev CANTINA 3.1.2. `initialize` checked only that the three module addresses were non-zero,
/// so a wrong or CODELESS address left the controller unusable and unrecoverable without an
/// upgrade. The asymmetry was visible in this same file: `setLossSource` already refused a
/// non-contract. A code-length check alone would not catch a wrong-but-CONTRACT address,
/// which is the misconfiguration that actually happens, so each module is also PROBED.
error Controller_ModuleNotResponding(address module);
/// @dev THE IMPLEMENTATION INITIALISER LOCK — LOAD-BEARING, DO NOT DELETE. Without it the
/// logic contract behind the proxy is initialisable by anyone, which is finding A-01's
/// shape and the house convention every other implementation in `contracts/src` follows.
/// AUDIT NOTE (R18): R17's 63-guard deletion campaign did NOT enumerate this line, and it
/// survived the full non-fork suite when deleted — which also falsified R17's claim, made
/// on `mint`, that "every other guard in this file reds".
/// `test_R18_G64_theImplementationInitialiserIsLocked` is the falsifier that was missing.
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/// @notice Initializes the controller.
/// @param admin Governance timelock.
/// @param guardian Emergency pauser.
/// @param upgrader Upgrade authority (timelock).
/// @param usdfr The USDfr token (this contract must hold its MINTER_ROLE).
/// @param compliance The compliance registry (KYC gate).
/// @param reserves The ReserveManager (this contract must hold its CONTROLLER_ROLE).
/// @dev The credit-layer endpoint maps (`setYieldSink`, `setLossSource`) start EMPTY, so a
/// freshly initialized controller can mint no yield and burn no loss until governance
/// names the endpoints. That is deliberate fail-closed wiring (CLAUDE.md prime
/// directive 4): an unwired controller refuses credit-layer supply changes rather than
/// accepting arbitrary ones. `Validate.s.sol` asserts the production wiring post-deploy.
function initialize(
address admin,
address guardian,
address upgrader,
address usdfr,
address compliance,
address reserves
) external initializer {
if (
admin == address(0) || guardian == address(0) || upgrader == address(0) || usdfr == address(0)
|| compliance == address(0) || reserves == address(0)
) revert Controller_ZeroAddress();
// CANTINA 3.1.2. Non-zero was not enough; see `Controller_ModuleNotResponding`.
_requireModuleResponds(usdfr, abi.encodeWithSignature("totalSupply()"));
_requireModuleResponds(reserves, abi.encodeWithSignature("recognizedBackingValue()"));
_requireModuleResponds(compliance, abi.encodeWithSignature("isAllowed(address)", address(0)));
__AccessControl_init();
__Pausable_init();
__ReentrancyGuard_init();
__UUPSUpgradeable_init();
_grantRole(DEFAULT_ADMIN_ROLE, admin);
_grantRole(Roles.GUARDIAN_ROLE, guardian);
_grantRole(Roles.UPGRADER_ROLE, upgrader);
ControllerStorage storage $ = _storage();
$.usdfr = IUSDfr(usdfr);
$.compliance = IComplianceRegistry(compliance);
$.reserves = IReserveManager(reserves);
}
// ── User paths (KYC-gated) ───────────────────────────────────────────
/// @inheritdoc IMintRedeemController
/// @dev THE INDEPENDENT DELIVERY CHECK (AUDIT FIX R16-L2) — DO NOT DELETE. Before this
/// round `mint` derived BOTH sides of its own safety check from the same module: it
/// minted exactly what `ReserveManager.depositUSDC` REPORTED, then asserted backing
/// using ReserveManager's own tally of that same deposit. A ReserveManager that
/// credited its ledger without taking custody of the cash — a skimming implementation,
/// a fee-on-transfer or blocklisting USDC, a botched upgrade — satisfied both sides of
/// the check with the money missing. The controller now measures the RESERVE'S OWN USDC
/// BALANCE across the call, which is a fact no ReserveManager function can report about
/// itself, and requires the delivered units and the credited value to agree with what
/// the user was charged.
///
/// RECOGNITION IS MEASURED TOO (AUDIT FIX R18) — DO NOT DELETE
/// `Controller_DepositNotRecognized`. R17 measured two of the three facts a mint depends
/// on: CUSTODY (`delivered == usdcAmount`, the reserve's own USDC balance really rose) and
/// the REPORTED CREDIT (`usdfrOut == usdcAmount * SCALE`). Neither says the reserve BOOKED
/// the deposit as backing, and the only thing covering that was `_assertDeficitNotWorsened`
/// — a NON-WORSENING rule, so a reserve that took the cash, reported the right credit and
/// never recognised it was caught only for the part of the gap EXCEEDING the standing
/// surplus. The undetected amount was exactly `backingValue() - totalUSDfr()`, and R17
/// WIDENED that window: because `mintableHeadroom()` nets out `seniorSubParShortfall()`,
/// the protocol is now designed to sit permanently on a surplus of exactly the retention.
/// The backing delta is therefore now measured directly and required to equal the credit,
/// which is a LEVEL-FREE check no standing surplus can pay for.
///
/// THE ALLOWANCE IS ZEROED (AUDIT FIX R17), AND IT IS NOT A FALSIFIABLE GUARD — R18
/// CORRECTED THIS PARAGRAPH, WHICH SAID THE OPPOSITE OF THE INLINE COMMENT ON THE LINE
/// ITSELF. R16 argued that no residual allowance was possible, because the delivery
/// equality refuses unless the reserve's balance rose by exactly `usdcAmount`, "which on
/// every reachable path is that allowance being spent in full". THAT ARGUMENT WAS UNSOUND,
/// and it was unsound for the same reason the guard three lines above exists: it assumed
/// the very module the guard exists to distrust. The equality constrains how much the
/// reserve's balance ROSE; it says nothing about WHERE the rise came from. But the guard
/// that CATCHES that reserve is the zero-DELTA check on this contract's own balance
/// (`Controller_CashStrandedOnController`), not the `forceApprove(…, 0)`;
/// `test_R17_L2b_aReserveThatSourcesTheDepositElsewhereIsRefused` reds the former and NOT
/// the latter. Read the inline comment on the line itself — it is the accurate one, and it
/// states the real reason the line is kept (stale-approval hygiene against L4-donated
/// USDC). Deleting it is safe against the whole suite; that is the honest statement and
/// finding M6 is why it has to be made rather than dressed up as protection.
///
/// SLITHER `reentrancy-balance` (High/Medium) FIRES HERE, AND IS ACCEPTED — R17 re-ran
/// `tools/run-slither-analysis.mjs` and added the entry to `contracts/slither-baseline.json`
/// against `MintRedeemController.mint`, which R16 had claimed was accepted while the gate
/// was in fact RED. This paragraph and the one on `_quoteRedeem` ARE the triage and must be
/// transcribed into `STATE.md` at merge, as CLAUDE.md §3.2 requires. It fires because a balance
/// read straddles an external call and gates a state change, which is the guard, not an
/// accident. Three things bound it: the function is `nonReentrant` (falsified by
/// `test_R17_G04_mintIsReentrancyLocked`, so that modifier is not an unfalsifiable
/// guard either); canonical USDC has no transfer callback; and the check is an EQUALITY,
/// so the manipulation direction is fail-CLOSED — an unsolicited donation to the reserve
/// mid-call makes `delivered` EXCEED `usdcAmount` and the mint reverts. The only
/// manipulation that passes is one in which the attacker funds the missing cash
/// themselves, which is not an attack.
function mint(uint256 usdcAmount) external nonReentrant whenNotPaused returns (uint256 usdfrOut) {
ControllerStorage storage $ = _storage();
_requireAccrualFresh($);
_requireKYC($, msg.sender);
// AUDIT FIX (R4-01). See `_requireCustodiedReserve`. 1:1 issuance into a reserve the
// protocol can already see is short sells a new claim on a hole. Deleting this line
// reopens that.
_requireCustodiedReserve($);
if (usdcAmount == 0) revert Controller_ZeroAmount();
(uint256 supplyBefore, uint256 backingBefore) = _supplyAndBacking($);
// AUDIT FIX (R16-M3) — LOAD-BEARING, DO NOT DELETE. The par mint window is closed
// whenever the protocol is under-backed for ANY reason, not just the R4-01 custody
// reason immediately above: a G3 conservative mark on deployed principal, or a residual
// deficit the cascade could not absorb, puts the protocol below par with custody
// perfectly intact, and `_requireCustodiedReserve` sees none of it. Selling a fresh 1:1
// claim there hands the new minter a sub-par instrument at par. Note the ASYMMETRY with
// `redeem`, which stays OPEN and re-prices: see the contract-level NatSpec for why that
// is deliberate and not an inconsistency.
if (supplyBefore > backingBefore) {
revert Controller_MintClosedWhileUnderBacked(supplyBefore, backingBefore);
}
IERC20 usdcToken = IERC20($.reserves.usdc());
uint256 custodyBefore = usdcToken.balanceOf(address($.reserves));
// A DELTA, NOT AN ABSOLUTE BALANCE, AND THE DIFFERENCE IS LOAD-BEARING. USDC can be sent
// to this contract by anyone at any time (finding L4), so a guard written as
// `balanceOf(this) != 0` would let one wei of donated USDC brick `mint` for everyone,
// permanently — a worse defect than the one it closes, and a free griefing vector. What is
// refused below is a change in this contract's balance ACROSS THE CALL.
uint256 selfBefore = usdcToken.balanceOf(address(this));
usdcToken.safeTransferFrom(msg.sender, address(this), usdcAmount);
usdcToken.forceApprove(address($.reserves), usdcAmount);
usdfrOut = $.reserves.depositUSDC(address(this), usdcAmount);
// NOT A GUARD, AND LABELLED AS SUCH DELIBERATELY (AUDIT FIX R17). The falsifiable guard
// for the residual-allowance finding is the ZERO-BALANCE check below; this line cannot be
// turned red by any deletion mutation, because every state that leaves an allowance
// standing also leaves cash standing and is refused there. That is not an assumption: it
// is the MEASURED result of R17's 63-mutation guard-deletion campaign, in which this is
// the ONE line of the 63 ENUMERATED GUARDS that survived the full non-fork suite with it
// deleted. R18 CORRECTS THE SENTENCE THAT FOLLOWED — R17 wrote "every other guard in this
// file reds", which was false: the campaign enumerated 63 guards, and at least one line
// that IS a guard was not among them (`constructor() { _disableInitializers(); }`, which
// also survived; R18 adds `test_R18_G64_theImplementationInitialiserIsLocked` so it no
// longer does). The claim that holds is the narrow one: of the 63 guards R17 enumerated,
// this is the only survivor. This line is kept for one reason only: so that USDC DONATED to
// this contract after the fact (the L4 stranding case, which no protocol path creates)
// cannot be pulled out by the reserve on a stale approval. Read it as hygiene, not as
// protection — that distinction is the whole of finding M6.
usdcToken.forceApprove(address($.reserves), 0);
uint256 custodyAfter = usdcToken.balanceOf(address($.reserves));
// The clamp is not decoration: `ControllerReserveDouble.Mode.DrainOnDeposit` takes the
// charge and forwards MORE than it took, so the reserve's balance FALLS across the call
// (`test_R17_G11_aReserveWhoseBalanceFallsAcrossTheDepositIsNamedNotPanicked`). Without
// it that state is an arithmetic panic instead of `Controller_DepositNotCustodied`.
uint256 delivered = custodyAfter < custodyBefore ? 0 : custodyAfter - custodyBefore;
if (delivered != usdcAmount || usdfrOut != usdcAmount * SCALE) {
revert Controller_DepositNotCustodied(usdcAmount, delivered, usdfrOut);
}
// AUDIT FIX (R17) — LOAD-BEARING, DO NOT DELETE. "The controller holds ZERO USDC at rest"
// was argued in R16 and asserted only against the HONEST reserve. Under the untrusted
// reserve the guard above already assumes, it is false: a reserve that funds the deposit
// from a third party satisfies the delivery equality with the user's cash still sitting
// here and a live allowance against it. Enforcing it makes the mint fail CLOSED instead.
// The comparison is an EQUALITY on the delta, so it is fail-closed in BOTH directions: the
// charge staying here is refused, and so is the reserve pulling MORE out of this contract
// than it was approved for.
uint256 selfAfter = usdcToken.balanceOf(address(this));
if (selfAfter != selfBefore) revert Controller_CashStrandedOnController(selfBefore, selfAfter);
// AUDIT FIX (R18) — LOAD-BEARING, DO NOT DELETE. The RECOGNITION leg of the R16-L2
// measurement. Custody and the reported credit are both checked above; NEITHER of them
// says the reserve booked the deposit as BACKING, and the only thing that covered
// recognition was `_assertDeficitNotWorsened`, whose rule is NON-WORSENING and therefore
// silently pays for any recognition gap up to the standing surplus. This is a DELTA
// equality on `totalBackingValue()` across the deposit leg, so no standing surplus can
// absorb it: `test_R18_F1_aStandingSurplusIsNoLongerABudgetForAnUncreditedDeposit` builds a
// reserve in `ControllerReserveDouble.Mode.DepositWithoutCrediting` on a book carrying
// exactly enough surplus to hide the whole deposit, and it is refused here. The equality is
// fail-closed in BOTH directions: a reserve that OVER-books the deposit is refused too.
// `depositUSDC` makes no external call that could move any other backing component (the
// reserve is `nonReentrant` and canonical USDC has no transfer callback), so the honest
// path is exact, not approximate.
uint256 backingAfterDeposit = $.reserves.totalBackingValue();
uint256 recognisedCredit = backingAfterDeposit < backingBefore ? 0 : backingAfterDeposit - backingBefore;
if (recognisedCredit != usdfrOut) {
revert Controller_DepositNotRecognized(usdfrOut, recognisedCredit);
}
$.usdfr.mint(msg.sender, usdfrOut);
_assertDeficitNotWorsened($, supplyBefore, backingBefore);
emit Minted(msg.sender, usdcAmount, usdfrOut);
}
/// @inheritdoc IMintRedeemController
/// @dev THE ONE-ARGUMENT FORM IS THE PAR-FLOOR FORM (AUDIT FIX R17) — LOAD-BEARING, DO NOT
/// "SIMPLIFY" IT TO `_redeem(usdfrAmount, 0)`. R16 turned the exit price from the
/// constant 1:1 into a live function of `backing/supply` and did not change this
/// signature, so every caller written against the old constant kept sending a
/// one-argument transaction and silently accepted whatever the ratio was at inclusion.
/// Several protocol paths lower backing in the same block and NONE of them is
/// timelocked: `ReserveManager.recordPrincipalWritedown` (CREDIT_ROLE, keeper-driven),
/// `reconcileIdleUSDC`/`writeDownIdleUSDC` (RESERVE_ADMIN), and a timelock's own
/// `recognizePrincipalImpairment`, whose ready transactions are permissionlessly
/// executable and publicly visible. Defaulting to the par floor means this form settles
/// at par or REVERTS; taking a haircut requires the caller to name the price they will
/// accept. A holder is never silently impaired.
function redeem(uint256 usdfrAmount) external nonReentrant whenNotPaused returns (uint256 usdcOut) {
// The par floor: one whole USDC unit per `SCALE` wei of USDfr actually burnable.
return _redeem(usdfrAmount, usdfrAmount / SCALE);
}
/// @inheritdoc IMintRedeemController
function redeem(uint256 usdfrAmount, uint256 minUsdcOut)
external
nonReentrant
whenNotPaused
returns (uint256 usdcOut)
{
return _redeem(usdfrAmount, minUsdcOut);
}
/// @inheritdoc IMintRedeemController
/// @dev THE DEADLINE (ADR-0034 W) — LOAD-BEARING, DO NOT DELETE, AND THIS IS THE CANONICAL
/// FORM. R16 turned `redeem` from a fixed-price operation into a variable-price one and
/// gave it neither a minimum-out nor a deadline; R17 shipped the minimum-out. A
/// minimum-out alone bounds the PRICE but not the TIME: a transaction that sits in the
/// mempool through a gas spike executes at whatever ratio holds whenever a builder chooses
/// to include it, and every path that moves that ratio down is UNTIMELOCKED and publicly
/// visible before it lands — `recordPrincipalWritedown` (CREDIT_ROLE, keeper-driven),
/// `reconcileIdleUSDC`/`writeDownIdleUSDC` (RESERVE_ADMIN), and a timelock's own
/// `recognizePrincipalImpairment`, whose ready transactions anyone may execute. A
/// redeemer who set `minUsdcOut` at a healthy mark and was not included for an hour hands
/// a searcher a free option: hold the transaction until the ratio moves, then include it.
/// ADR-0034 W requires this "whichever pricing basis is chosen", i.e. independently of the
/// junior draw.
///
/// THE ONE- AND TWO-ARGUMENT FORMS ARE LEFT DEADLINE-FREE ON PURPOSE. Silently giving an
/// existing signature a new expiry semantic is R16's own mistake repeated — every caller
/// written against the old signature would keep compiling and start behaving differently.
/// Integrators should migrate to this form; the older ones remain valid and unexpired.
function redeem(uint256 usdfrAmount, uint256 minUsdcOut, uint256 deadline)
external
nonReentrant
whenNotPaused
returns (uint256 usdcOut)
{
// Falsified by `test_Y_G08_theDeadlineRefusesAnExpiredRedemption`.
if (block.timestamp > deadline) revert Controller_DeadlinePassed(deadline, block.timestamp);
return _redeem(usdfrAmount, minUsdcOut);
}
/// @dev SUB-PAR REDEMPTION (AUDIT FIX R16-M3, AMENDED BY R17) — READ THIS BEFORE CHANGING THE
/// ARITHMETIC. `_quoteRedeem` pays the COVERAGE RATIO, not par. The old behaviour is
/// preserved exactly while `backing >= supply` (the overwhelmingly common state), and the
/// branch only bites once the protocol is genuinely short.
///
/// WHAT THIS GUARANTEES, STATED EXACTLY (R17 CORRECTION). Every rounding in the quote is
/// DOWN, so the redeemer is paid at most their pro-rata share and THE INSTANTANEOUS BOOK
/// COVERAGE RATIO left behind for the holders who did not redeem is unchanged or better.
/// That property is real — it is fuzzed by
/// `testFuzz_M3_aSubParExitNeverWorsensTheRatioForTheHoldersWhoStayed` — and it is the
/// ONLY thing this arithmetic promises.
///
/// WHAT THIS DOES NOT PROMISE, AND R16'S NATSPEC WRONGLY CLAIMED IT DID. The sentence
/// "this is the same protection without the freeze" was removed in R17 because it is
/// false in two specific ways an auditor must be told:
/// - COMPOSITION. Backing is not homogeneous. The exit is settled ENTIRELY in cash out
/// of the idle leg, at a ratio struck on a BLENDED mark, so a first mover converts a
/// part-liquid, part-impaired claim into 100% cash and the holders who stay are left
/// with a residue concentrated in the leg that is still marking. The instant path is
/// therefore FIRST-COME-FIRST-SERVED ON LIQUIDITY. It is not a run in VALUE terms; it
/// is a race in LIQUIDITY terms.
/// - SEQUENCING. The ratio is preserved AT THE CURRENT MARK. A conservative G3 mark
/// that is later DEEPENED — the ordinary shape of a workout — reallocates the extra
/// loss onto whoever did not move first.
/// Capping the instant exit at the redeemer's pro-rata share of the IDLE leg and queueing
/// the residue would close both. There is no USDfr->USDC queue (ADR-0018's
/// `RedemptionQueue` orders the sUSDfr leg, not this one), so the cap alone would convert
/// a full exit into a permanently partial one with no ordered claim on the remainder —
/// strictly worse for the holder. R16 and R17 recorded the choice between that, a queue
/// and the status quo as an OPEN Forest Road question, "raised, not taken".
///
/// THAT IS NO LONGER TRUE, AND THE DECISION IS NOW IMPLEMENTED HERE.
/// `ADR/0034-exit-pricing-in-cascade-order.md` (Status: ACCEPTED, Forest Road 2026-08-07,
/// amended by decision Y-bis 2026-08-08) decides it AGAINST the R16/R17 behaviour.
/// Decision X: all capital is at risk, senior included, but losses are borne "in cascade
/// order at all times", which puts unstaked USDfr holders LAST rather than outside the
/// §1.3 cascade. Decision Y-bis: the junior-netted price and the junior DRAW are not
/// alternatives — the residual price promises more than gross-marked backing and the
/// difference sits in the curator pool and the sGROVE backstop, so junior capital is drawn
/// AT THE MOMENT OF THE EXIT, in this transaction, and cascade order is enforced AT
/// SETTLEMENT rather than assumed.
///
/// WHAT THAT MEANS FOR THE TWO HONEST CAVEATS ABOVE. COMPOSITION is unchanged: the exit is
/// still settled entirely in cash out of the idle leg, so the instant path is still
/// first-come-first-served ON LIQUIDITY. What HAS changed is the VALUE half: a holder
/// exiting while junior capital stands is now made whole out of that junior capital
/// instead of being haircut at the gross mark. SEQUENCING is unchanged and is the cost
/// ADR-0034 accepts EXPLICITLY: the mark that triggers a draw is conservative and
/// REVERSIBLE, so a draw crystallises junior capital against a loss that may never
/// materialise, and the beneficiary has already exited. Forest Road accepted that on
/// 2026-08-08 in preference to a senior absorbing a loss the junior contracted to take
/// first. `mintableHeadroom()` retains the standing prepayment so the reversal does not
/// become sUSDfr yield.
///
/// DECISION W IS NOW COMPLETE: `minUsdcOut` shipped in R17, and the DEADLINE it also
/// requires ships on `redeem(uint256,uint256,uint256)`. DECISION Z is encoded as a
/// stateful campaign in `test/invariant/CascadeOrderedExitInvariants.t.sol`, with a
/// falsification test that reds it against a draw that draws nothing.
///
/// SEE `_drawJuniorForExit` AND `_exitDrawTarget` FOR THE MECHANISM, AND `_quoteRedeem`
/// FOR THE THREE THINGS THAT REMAIN OUTSTANDING (`previewRedeem`'s undrawn floor, the
/// class-less layer 1, and the draw stopping at layer 2).
///
/// WHY IT IS SAFE TO PRICE OFF `totalBackingValue()` HERE. `_requireCustodiedReserve`
/// has already refused if there is any observable custody gap, so at this line
/// `recognizedBackingValue() == totalBackingValue()` by construction. Pricing off the
/// recorded basis therefore quotes the same number as the recognition-aware basis while
/// keeping ONE basis across the quote and the closing assertion. If
/// `_requireCustodiedReserve` is ever relaxed, this must move to
/// `recognizedBackingValue()` in the same change. Note `previewRedeem` uses the
/// RECOGNITION-AWARE basis precisely because it is NOT behind that guard.
///
/// THE OUTFLOW DELIVERY MEASUREMENT (AUDIT FIX R17) — DO NOT DELETE. R16-L2 installed an
/// independent measurement on `mint` and left `redeem` deriving BOTH sides of its safety
/// check from the same module: the reserve lowers its own backing tally in `releaseUSDC`
/// and `_assertDeficitNotWorsened` reads that same tally back. A reserve that books the
/// release correctly and under-delivers the cash satisfied every guard — on the leg where
/// the holder's USDfr is ALREADY BURNED and the loss is irreversible. The redeemer's own
/// balance is now measured across the release. Same threat model as `mint`'s (a botched
/// upgrade, a blocklisting or fee-on-transfer USDC, a skimming implementation), same
/// fail-closed direction: an unsolicited donation to the redeemer mid-call makes the
/// delta exceed `usdcOut` and reverts.
///
/// THE MEASUREMENT WINDOW MUST CONTAIN `releaseUSDC` AND NOTHING ELSE (AUDIT FIX R18) — DO
/// NOT MOVE `payeeBefore` BACK ABOVE THE BURN. R17 opened the window before
/// `$.usdfr.burn(...)`, and `USDfr._update` fires the participation-points hook inside
/// every burn, with `gasleft() - 100_000` available to it. The token wraps that hook in
/// `try/catch` under an explicit protocol-wide rule — "a points-module failure must never
/// block a USDfr transfer, mint, or burn" (finding C4-USDFR-01) — but a hook that moved ONE
/// WEI of USDC to the redeemer broke the equality below, and the revert happened HERE,
/// outside that `try/catch`. R17 therefore handed a governance-set module the power to
/// brick every redemption while ordinary transfers kept working: the token's fail-open
/// guarantee held everywhere except the leg running through this guard. With the burn
/// hoisted out of the window the only external call inside it is `releaseUSDC`, and the
/// strict equality is preserved — which still catches a reserve that OVER-pays cash while
/// under-booking its ledger, something a `settled < usdcOut` relaxation would not.
/// GENERAL RULE, for anyone extending this function: no call that a redeemer or a
/// governance-set module can influence may be added between `payeeBefore` and `payeeAfter`.
/// SLITHER `reentrancy-balance` fires TWICE here for
/// the same reason it fires on `mint` — a balance read straddling an external call and
/// gating a state change IS the guard — and both entries are carried in
/// `contracts/slither-baseline.json` against `MintRedeemController._redeem`.
function _redeem(uint256 usdfrAmount, uint256 minUsdcOut) private returns (uint256 usdcOut) {
ControllerStorage storage $ = _storage();
_requireAccrualFresh($);
_requireKYC($, msg.sender);
// AUDIT FIX (R4-01) — THE FINDING ITSELF. See `_requireCustodiedReserve`. Deleting this
// line restores first-come-first-served exits out of a reserve whose USDC ledger is
// known to be a lie — which sub-par pricing CANNOT protect against, because the price it
// would quote comes from that same lying ledger.
_requireCustodiedReserve($);
if (usdfrAmount == 0) revert Controller_ZeroAmount();
(uint256 supplyBefore, uint256 backingBefore) = _supplyAndBacking($);
// AUDIT FIX (ADR-0034 Y-bis) — THE ATOMIC JUNIOR DRAW. It runs BEFORE the quote on purpose:
// the ADR requires that "a quote that cannot be funded must not be issued", and striking
// the price on the draw's MEASURED outcome makes an unfundable quote unrepresentable
// rather than merely refused. See `_drawJuniorForExit`.
uint256 drawn = _drawJuniorForExit($, (usdfrAmount / SCALE) * SCALE, supplyBefore, backingBefore);
uint256 usdfrIn;
(usdcOut, usdfrIn) = _quoteRedeem(usdfrAmount, supplyBefore, backingBefore, drawn);
// Every direct exit remains frozen until this arm is resolved. The result is
// independent of permissionless changes to junior capacity; refusal is atomic.
_requireNoArmedExit($, usdcOut, usdfrIn);
if (usdcOut == 0) {
// AUDIT FIX (R17). A protocol whose backing has fallen to zero used to answer
// `Controller_AmountTooSmall` — an error whose plain meaning is "your amount is too
// small" when the truth is "there is nothing left to pay you". Distinguish them.
if (backingBefore == 0 && supplyBefore != 0) revert Controller_NoRedeemableBacking(supplyBefore);
// USDC has six decimals while USDfr has eighteen, so a redemption worth less than one
// whole USDC unit cannot be settled at all. See `previewRedeem` for the exact floor
// and why leaving the dust in the holder's wallet is the correct behaviour (R16-L3).
revert Controller_AmountTooSmall(usdfrAmount);
}
// AUDIT FIX (R17) — LOAD-BEARING, DO NOT DELETE. The caller's price floor. `previewRedeem`
// is advisory across transactions; this is the only thing that BINDS the settlement.
if (usdcOut < minUsdcOut) revert Controller_SlippageExceeded(usdcOut, minUsdcOut);
IERC20 usdcToken = IERC20($.reserves.usdc());
// Burn (supply down) before releasing backing; the deficit rule is asserted after.
$.usdfr.burn(msg.sender, usdfrIn);
// AUDIT FIX (R18) — THE WINDOW OPENS HERE, AFTER THE BURN, ON PURPOSE. See this function's
// NatSpec: the burn fires USDfr's deliberately FAIL-OPEN points hook, and a hook that moved
// one wei of USDC to the redeemer inside the window turned this guard into a redemption
// kill switch that the token's own `try/catch` could not absorb.
uint256 payeeBefore = usdcToken.balanceOf(msg.sender);
$.reserves.releaseUSDC(msg.sender, usdcOut);
uint256 payeeAfter = usdcToken.balanceOf(msg.sender);
// The clamp is falsified by `ControllerReserveDouble.Mode.ClawbackRelease`, a reserve that
// debits the redeemer on a standing approval instead of paying them; without it that state
// is an arithmetic panic rather than `Controller_RedemptionNotSettled`.
uint256 settled = payeeAfter < payeeBefore ? 0 : payeeAfter - payeeBefore;
if (settled != usdcOut) revert Controller_RedemptionNotSettled(usdcOut, settled, usdfrIn);
// AUDIT FIX (ADR-0034 Y-bis) — THE ANCHOR IS RE-BASED ON THE POST-DRAW SUPPLY, AND THAT IS
// LOAD-BEARING. `supplyBefore` was read BEFORE the junior draw burned `drawn`, so passing
// it here would hand this check exactly `drawn` wei of slack to worsen into — and would
// hide an under-delivering reserve behind junior capital, on the leg where the holder's
// USDfr is ALREADY BURNED and the loss is irreversible. Anyone "simplifying" this back to
// `supplyBefore` silently disables the guard in exactly the state it exists for.
// Falsified by `test_Y_G07_theDeficitAnchorIsRebasedOnThePostDrawSupply`
// (test/audit/ADR0034Y_ExitDrawAnchor.t.sol).
_assertDeficitNotWorsened($, supplyBefore - drawn, backingBefore);
uint256 valuePaid = usdcOut * SCALE;
if (valuePaid < usdfrIn) {
// AUDIT FIX (R17) — LOAD-BEARING, DO NOT DELETE. See `seniorSubParShortfall`. This is
// the crystallised, IRREVERSIBLE part of a REVERSIBLE mark. Recording it is what stops
// a later `releasePrincipalImpairment` turning the exiter's loss into vault yield.
uint256 crystallised = usdfrIn - valuePaid;
uint256 cumulative = $.subParShortfall + crystallised;
$.subParShortfall = cumulative;
emit SeniorShortfallCrystallised(msg.sender, crystallised, cumulative);
emit SubParRedemption(msg.sender, usdfrIn, usdcOut, supplyBefore, backingBefore);
}
emit Redeemed(msg.sender, usdfrIn, usdcOut);
}
// ── Credit-layer paths (wired in Phases E/G) ─────────────────────────
/// @notice Record the supply/backing baseline for a yield mint whose backing leg moves FIRST.
///
/// @dev WHY THIS EXISTS. `_assertDeficitNotWorsened` and its recognised twin are NON-WORSENING
/// checks, and they are correct. What was wrong was WHERE they measured from.
/// `WaterfallEngine.capitalizePik` raises backing (`recordPikCapitalization`) and only then
/// raises supply here, so `mintYield`'s own snapshot was taken with backing ALREADY moved.
/// For a standing deficit D and a capitalisation of `a` it read deficitBefore as
/// max(0, D - a) against a deficitAfter of D, called a pair that changes the deficit by
/// EXACTLY ZERO a worsening, and refused. Measured: one USDC unit of conservative mark on
/// an unrelated facility froze every PIK capitalisation in the book.
///
/// THIS DOES NOT WEAKEN THE RULE, IT MEASURES IT PROPERLY. Both assertions still run, and
/// they now run against the TRUE pre-operation state, so the mint is admitted only if the
/// pair really is deficit-neutral end to end. A caller that raises backing and then mints
/// more than it credited still fails. A paired mint preserves recognized surplus while
/// retention is active and requires the retention obligation to equal its opening value.
/// Existing undercoverage can remain unchanged; an intervening retention change cannot
/// use an older baseline. Ordinary yield mints still enforce the absolute retention floor.
///
/// The fee twin never needed this because it CLAMPS to `mintableHeadroom()` and withholds;
/// PIK cannot clamp, because a partial mint leaves backing above supply by the withheld
/// amount and that phantom surplus is absorbed pre-cascade.
function beginPairedYield() external onlyRole(Roles.CREDIT_ROLE) nonReentrant whenNotPaused {
ControllerStorage storage $ = _storage();
_requireAccrualFresh($);
if ($.pairedYieldCaller != address(0)) revert Controller_PairedYieldAlreadyOpen($.pairedYieldCaller);
(uint256 supplyBefore, uint256 backingBefore) = _supplyAndBacking($);
$.pairedYieldCaller = msg.sender;
$.pairedSupplyBefore = supplyBefore;
$.pairedBackingBefore = backingBefore;
$.pairedRecognizedBefore = $.reserves.recognizedBackingValue();
$.pairedRetentionBefore = $.subParShortfall + $.reserves.exitPrepaidAbsorption();
emit PairedYieldOpened(msg.sender, supplyBefore, backingBefore);
}
/// @notice Governance escape for a paired-yield baseline stranded by a reverted operation.
/// @dev Mirrors `sUSDfr.clearStaleFeeOperation`. THE EARLIER VERSION OF THIS NOTE CLAIMED A
/// STRANDED BASELINE COULD ONLY EVER BE STRICTER. That was false: the deficit is not
/// monotone, so a snapshot taken in a WORSE state would be a LOOSER baseline for a later
/// mint. `beginPairedYield` therefore refuses to open a second baseline while one stands,
/// `mintYield` consumes it so it can never span two mints, and this is the governance
/// escape for the only way one can be stranded: an operation that opened a baseline and
/// then reverted after the state had moved.
function clearStalePairedYield() external onlyRole(DEFAULT_ADMIN_ROLE) {
_requireAccrualFresh(_storage());
ControllerStorage storage $ = _storage();
address caller = $.pairedYieldCaller;
_clearPairedYield($);
emit PairedYieldCleared(caller);
}
function _clearPairedYield(ControllerStorage storage $) private {
$.pairedYieldCaller = address(0);
$.pairedSupplyBefore = 0;
$.pairedBackingBefore = 0;
$.pairedRecognizedBefore = 0;
$.pairedRetentionBefore = 0;
}
/// @inheritdoc IMintRedeemController
/// @dev THE `to` CONSTRAINT (AUDIT FIX R16-M1) — LOAD-BEARING, DO NOT DELETE. `mintYield`
/// constrained `to` in no way, and `burnLoss` constrained `from` in no way. The two
/// COMPOSED into arbitrary confiscation — burn a named holder's balance, mint the same
/// amount to an attacker — and `_assertBacking` could not detect it BY CONSTRUCTION,
/// because it compared two global aggregates and the pair left both unchanged. It was
/// reproduced on a mainnet fork with 250,000 real USDC borrowed from the Maker PSM.
///
/// WHAT CONSTRAINING THE ENDPOINTS ACTUALLY BOUGHT, STATED HONESTLY (R17 CORRECTION).
/// R16 claimed the endpoints "break the composition at both ends". That overstates it and
/// the overstatement is itself a defect, so here is the true statement. The aggregate
/// blindness is STRUCTURAL and untouched: `burnLoss` carries no solvency assertion at all
/// (correctly — see its NatSpec) and this function's assertion compares two global
/// aggregates, so a burn of X followed by a mint of X is invisible to it BY CONSTRUCTION.
/// What the endpoint lists removed is the ARBITRARY-VICTIM form: `from` must now be a
/// governance-named loss source AND (R17) a CONTRACT, so no user wallet is seizable, and
/// the residual composition can only reach the `sUSDfr` vault, whose burn is pro-rata
/// across every senior depositor. What `Roles.LOSS_BURNER_ROLE` removed is the
/// SINGLE-ROLE form: the composition now needs BOTH `LOSS_BURNER_ROLE` and `CREDIT_ROLE`,
/// which `Deploy.s.sol` deliberately splits across `DefaultManager` and `WaterfallEngine`.
/// THAT SPLIT IS LOAD-BEARING AND MUST NEVER BE RELAXED "FOR SYMMETRY" — it is one
/// `grantRole` deep, and `Validate.s.sol` asserts it post-deploy.
///
/// WHY A DEDICATED LIST AND NOT `ComplianceRegistry.isProtocolExempt`. That list looks
/// like the right one and is not: it is already overloaded as the sanctions-bypass set,
/// the USDfr emergency-pause carve-out, the `PointsModule` ineligibility set and the
/// `sUSDfr` fee-recipient validity set. Hanging burn authority off it means a
/// compliance-motivated de-listing silently disables the loss cascade, and a listing
/// made to keep a module transferable silently grants it burn authority. Separate
/// concerns get separate lists.
///
/// WHENNOTPAUSED IS DELIBERATE AND ASYMMETRIC WITH `burnLoss` (AUDIT FIX R16-L1). A
/// guardian pause must never leave supply EXPANSION available while user exits are
/// frozen. This mirrors the rule `USDfr._update` already enforces on the token itself
/// ("mints stay closed even to a listed module, because a pause must never permit
/// supply EXPANSION"), so `WaterfallEngine`'s interest leg was already unavailable
/// under a USDfr pause; this makes a controller pause say the same thing instead of
/// being a one-way valve that closes the user inflow and leaves the credit-layer
/// inflow open. R17 removed the LIVENESS cost of that choice without weakening it:
/// `mintableHeadroom()` reads zero while paused, so `WaterfallEngine._routeInterest`
/// clamps to zero and WITHHOLDS instead of reverting, and an ordinary borrower repayment
/// still settles under a controller pause. See `pause` and `mintableHeadroom`.
///
/// AUDIT FIX (R18): R17 APPLIED THAT ONLY TO HALF THE PAUSE SURFACE. `mintableHeadroom()`
/// read this contract's `paused()` and nothing else, while the SAME guardian address holds
/// `GUARDIAN_ROLE` on `USDfr` (`Deploy.s.sol` grants both), and `USDfr._update` refuses
/// every mint under a token pause — its `protocolLeg` carve-out requires
/// `from != address(0)`, so a mint can never qualify for it. One un-timelocked
/// `USDfr.pause()` therefore still reverted the yield leg, and because
/// `WaterfallEngine.distribute` is atomic it took the principal leg, the attestation
/// spend, the exposure release and the lifecycle transition down with it — the precise
/// harm the clamp exists to prevent, reached through the pause the clamp could not see.
/// `mintableHeadroom()` now reads BOTH pauses, so either one withholds instead of
/// reverting.
///
/// BOTH BASES ARE ASSERTED (AUDIT FIX R17) — DO NOT DELETE EITHER ASSERTION. This was the
/// one supply-EXPANDING path with no recognition-aware check of any kind. R16's comment
/// below said "while it is short it refuses outright"; that was true only of the RECORDED
/// deficit. Under an unreconciled custody shortfall — the R4-01 state, in which `mint`
/// and `redeem` both revert and `backingInvariantHolds()` publishes FALSE — the recorded
/// basis still reported the protocol whole, so the credit layer could mint fresh USDfr
/// against cash the reserve could already see was absent, and `recognizedDeficit()` rose
/// by the full amount minted while the predicate passed. That is R4-01's "sells a new
/// claim on a hole" reached through the credit door, and it is the L1 one-way-valve shape
/// on the recognition axis. `burnLoss` is deliberately NOT gated the same way: it only
/// ever LOWERS supply, and a recognition-aware assertion there would revert the C-01
/// cascade's own burns (see `_requireCustodiedReserve`). The asymmetry is now provable
/// rather than asserted — `test_R17_B02_burnLossStaysOpenUnderARecognisedShortfall` pins
/// it.
function mintYield(address to, uint256 amount) external onlyRole(Roles.CREDIT_ROLE) nonReentrant whenNotPaused {
ControllerAccrualLib.mintYield(_storage(), to, amount, address(0), 0);
}
/// @inheritdoc IMintRedeemController
function mintYieldSplit(address senior, uint256 total, address feeRecipient, uint256 fee)
external
onlyRole(Roles.CREDIT_ROLE)
nonReentrant
whenNotPaused
{
ControllerStorage storage $ = _storage();
if ($.pairedYieldCaller != msg.sender) revert Controller_PairedYieldRequired();
ControllerAccrualLib.mintYield($, senior, total, feeRecipient, fee);
}
/// @inheritdoc IMintRedeemController
/// @dev THE `from` CONSTRAINT (AUDIT FIX R16-M1/M2) — LOAD-BEARING, DO NOT DELETE. See
/// `mintYield` for the confiscation composition this half closes. It also answers a
/// second finding on its own: `USDfr.burn` takes NO ALLOWANCE, so an unconstrained
/// `from` made the capital-free cure for a shortfall a FORCED, NON-PRO-RATA seizure
/// from one named holder while an identically-placed holder paid nothing.
///
/// WHAT IS AND IS NOT PROMISED HERE (R17 CORRECTION). R16 wrote that "the only reachable
/// burns are the cascade's own". That described the DEPLOYED WIRING, not the reachable
/// set: `setLossSource` was a plain DEFAULT_ADMIN setter that accepted any non-zero
/// address including a bare EOA, so one routine-looking timelock transaction restored the
/// seizure this function is supposed to have closed — and the repo's own fixture listed
/// an EOA. R17 makes the setter refuse a CODELESS account, mirroring
/// `ReserveManager.setLossAbsorber`/`setLossController`, so the claim is now a property of
/// the CODE for every externally-owned account: no user wallet is seizable, allowance or
/// no allowance. It remains a property of the WIRING for contracts — governance can still
/// name a contract that holds USDfr — so the honest statement is: the only reachable burns
/// are from governance-named CONTRACT endpoints, which `Deploy.s.sol` sets to
/// `DefaultManager` (burning junior capital it has already received into ITSELF) and the
/// `sUSDfr` vault (pro-rata by construction, because it moves the vault's exchange rate
/// for every senior depositor at once), and which `Validate.s.sol` asserts post-deploy.
///
/// LEAST PRIVILEGE — `Roles.LOSS_BURNER_ROLE`, NOT `Roles.CREDIT_ROLE`. Verified by
/// grep at R16: every `burnLoss` call site in `src/` is in `DefaultManager`, passing
/// `address(this)` or `$.vault`. `WaterfallEngine` was granted `CREDIT_ROLE` on this
/// contract by `Deploy.s.sol` and therefore held a burn power IT NEVER USED. Splitting
/// the role removes that power from the engine entirely, so a compromise of the
/// repayment path cannot reach the burn path at all. `Validate.s.sol` asserts the
/// engine does NOT hold `LOSS_BURNER_ROLE`.
///
/// NO BACKING ASSERTION HERE, AND THAT IS THE FIX, NOT AN OMISSION (AUDIT FIX R16-M6).
/// This function previously asserted the backing invariant. Burning strictly LOWERS
/// `totalSupply` and cannot touch `backingValue` — the contract is `nonReentrant`, and
/// nothing on the burn path can raise supply or lower backing — so the assertion was
/// unfalsifiable: no reachable state could make it fire. That was proved empirically,
/// and it is exactly why the earlier `Controller_LossBurnDeficitMismatch` guard could be
/// DELETED IN FULL with the entire deterministic and invariant suite green. A guard no
/// test can red is not protection; it is a comment that an auditor will read as
/// protection. This round removes it and states the proof instead. The guards that
/// remain on this function — the role, the endpoint list, the zero-amount check — are
/// each proved by a deletion mutation.
///
/// NOT `whenNotPaused`, DELIBERATELY. Loss absorption is the one supply path that must
/// never be pausable: a guardian pause that stopped the cascade would leave a recognised
/// loss unallocated for the whole pause. `USDfr._update`'s emergency carve-out makes the
/// same choice for the same reason.
function burnLoss(address from, uint256 amount) external onlyRole(Roles.LOSS_BURNER_ROLE) nonReentrant {
if (amount == 0) revert Controller_ZeroAmount();
ControllerStorage storage $ = _storage();
ControllerAccrualLib.authorizeLossBurn(address($.accrual), from, amount);
if (!$.lossSource[from]) revert Controller_NotLossSource(from);
$.usdfr.burn(from, amount);
emit LossBurned(from, amount);
}
// ── Governance: credit-layer endpoints (AUDIT FIX R16-M1) ────────────
/// @notice Authorizes (or revokes) an address as a destination for `mintYield`.
/// @dev Timelocked governance only. Production wiring is the `sUSDfr` vault and the protocol
/// fee recipient; `Deploy.s.sol` sets both and `Validate.s.sol` asserts them. Zero is
/// refused so `mintYield(address(0), …)` can never be enabled, which is what lets that
/// function drop its own zero-address check instead of carrying an unreachable one.
/// @param account The address that may receive yield mints.
/// @param authorized True to authorize, false to revoke.
function setYieldSink(address account, bool authorized) external onlyRole(DEFAULT_ADMIN_ROLE) {
_requireAccrualFresh(_storage());
if (account == address(0)) revert Controller_ZeroAddress();
_storage().yieldSink[account] = authorized;
emit YieldSinkUpdated(account, authorized);
}
/// @notice Authorizes (or revokes) an address as a source for `burnLoss`.
/// @dev Timelocked governance only. Production wiring is `DefaultManager` (which burns the
/// junior capital it has already received into itself) and the `sUSDfr` vault (cascade
/// layer 3, pro-rata by construction). Zero is refused for the same reason as
/// `setYieldSink`.
///
/// THE CONTRACT CHECK (AUDIT FIX R17) — LOAD-BEARING, DO NOT DELETE. `burnLoss` burns
/// with NO ALLOWANCE and carries no backing assertion, and it is deliberately not
/// pausable, so neither the invariant nor a guardian can stop it. Listing an EOA here is
/// therefore a one-transaction, governance-reachable restoration of finding M2 — a
/// forced, non-pro-rata seizure of one named holder — dressed as routine wiring in a
/// timelock queue, which reads very differently from an upgrade. Every production loss
/// source is a protocol module; no user wallet is ever one. `ReserveManager`'s sibling
/// setters (`setLossAbsorber`, `setLossController`) already refuse a codeless address and
/// this is the same constraint. It is deliberately NOT applied to `setYieldSink`, which
/// legitimately names the Forest Road fee-recipient treasury and may be an EOA — that
/// half of the M1 composition credits an address, it does not seize one.
///
/// A CODE CHECK ALONE IS NOT "NO USER WALLET" AFTER PECTRA (AUDIT FIX R18) — DO NOT DELETE
/// THE DELEGATION-DESIGNATOR CHECK. R17 wrote that refusing a codeless account made the
/// claim "a property of the CODE for every externally-owned account: no user wallet is
/// seizable". THAT WAS FALSE ON THE DEPLOYMENT TARGET. EIP-7702 has been live on Ethereum
/// L1 (ADR-0009) since Pectra in May 2025: an ordinary key-controlled EOA that signs a
/// delegation carries a 23-byte code field of the form `0xef0100 ++ address`, so
/// `EXTCODESIZE` returns 23 and R17's check ADMITTED IT. Every MetaMask smart account,
/// Ambire wallet and gas-sponsored onboarding flow produces exactly that shape, so finding
/// M2 — a forced, allowance-free, non-pro-rata seizure of one named holder, unstoppable by
/// the guardian because `burnLoss` is deliberately not pausable and carries no backing
/// assertion — was still one routine-looking timelock transaction away for precisely the
/// class of wallet the guard names.
///
/// WHY THE FIRST BYTE IS SUFFICIENT AND A BOUND-BACK PROBE WAS NOT CHOSEN. EIP-3541 has
/// forbidden deploying any code beginning with `0xEF` since London, so no legitimately
/// deployed contract can collide with the designator prefix; refusing a leading `0xEF`
/// byte therefore excludes delegated EOAs without excluding any real module. The stronger
/// alternative — requiring the candidate to answer a bound-back probe — was NOT taken
/// because the two production loss sources (`DefaultManager` and the `sUSDfr` vault) do not
/// implement such a probe and adding one to them is a cross-module change; it is recorded
/// here as the follow-up if governance wants "cannot be wired by accident" rather than
/// "cannot be a wallet".
///
/// THE HONEST CLAIM IS THEREFORE: no CODELESS account and no DELEGATED EOA can be named a
/// loss source. It remains a property of the WIRING, not the code, that the named contract
/// is one whose burn is pro-rata.
/// @param account The address `burnLoss` may burn from. Must have code, and must not be an
/// EIP-7702 delegated EOA.
/// @param authorized True to authorize, false to revoke.
function setLossSource(address account, bool authorized) external onlyRole(DEFAULT_ADMIN_ROLE) {
_requireAccrualFresh(_storage());
if (account == address(0)) revert Controller_ZeroAddress();
// Only AUTHORIZATION is constrained. Revocation must never be blocked by the state of the
// account being revoked — a governance kill-switch that a self-destructed endpoint could
// disable would be a worse defect than the one this closes.
if (authorized) {
if (account.code.length == 0) revert Controller_LossSourceNotContract(account);
if (_isDelegatedEOA(account)) revert Controller_LossSourceIsDelegatedEOA(account);
}
_storage().lossSource[account] = authorized;
emit LossSourceUpdated(account, authorized);
}
/// @dev AUDIT FIX (R18) — LOAD-BEARING, DO NOT DELETE. True if `account` carries an EIP-7702
/// delegation designator, i.e. an ordinary EOA whose key signed a `SetCode` authorization.
/// The designator is EXACTLY 23 bytes and EXACTLY `0xef0100 ++ delegate`; EIP-3541 makes a
/// leading `0xEF` undeployable for real contract code, so this cannot false-positive on a
/// protocol module — `test_R18_C2_a23ByteContractThatIsNotADesignatorIsStillNameable`
/// pins that half. The refusal itself is falsified by
/// `test_R18_C2_a7702DelegatedWalletCannotBeNamedALossSource`, which MODELS the delegation
/// with `vm.etch` rather than signing one, so the property is pinned on the repo's default
/// `cancun` profile. What matters is the on-chain CODE FIELD, which is byte-identical
/// either way; that test carries its own control showing the same address REFUSED as a
/// plain EOA and ADMITTED by R17's rule once the designator is present.
function _isDelegatedEOA(address account) private view returns (bool) {
if (account.code.length != 23) return false;
bytes3 head;
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, 0)
extcodecopy(account, ptr, 0, 3)
head := mload(ptr)
}
return head == bytes3(0xef0100);
}
// ── Guardian ─────────────────────────────────────────────────────────
/// @notice Pauses the user mint/redeem paths and the credit-layer YIELD MINT. Emergency use
/// only.
/// @dev AUDIT FIX (R16-L1) corrected both the code and this NatSpec. A pause closes every
/// path that ISSUES USDfr (`mint`, `mintYield`) and the user exit (`redeem`); it
/// deliberately leaves `burnLoss` open, because loss absorption must never be pausable.
/// Pausing therefore cannot expand supply and cannot be used to freeze the cascade.
/// Note this is a SEPARATE pause from `USDfr.pause()`; the token's own pause closes the
/// user legs in both directions via `USDfr._update`'s protocol-leg carve-out.
///
/// WHAT A PAUSE DOES TO THE REPAYMENT PATH (AUDIT FIX R17 — STATED, BECAUSE R16 DID NOT).
/// `WaterfallEngine.distribute` is atomic and calls `mintYield` on every payment carrying
/// interest, so R16's `whenNotPaused` silently made a single un-timelocked GUARDIAN key
/// able to stop EVERY borrower repayment — principal leg, attestation spend, exposure
/// release and lifecycle transition included — and with it the ordinary interest payments
/// that are the protocol's only native cure for a deficit. R17 keeps the modifier (supply
/// expansion must stay closed) and removes the coupling: `mintableHeadroom()` reads ZERO
/// while paused, so `_routeInterest` clamps the distribution to zero, emits
/// `InterestWithheldForBackingRepair` and settles. The cash still lands in the reserve as
/// backing; only the YIELD is suspended.
///
/// R18 FINISHED THAT FIX ON BOTH AXES, BECAUSE R17 HAD DONE HALF OF EACH.
/// - THE OTHER PAUSE. R17's clamp read only THIS contract's `paused()`. The same
/// guardian address holds `GUARDIAN_ROLE` on `USDfr` too (`Deploy.s.sol` grants both),
/// and `USDfr._update` refuses every mint under a token pause, so one un-timelocked
/// `USDfr.pause()` still reverted every interest-bearing `distribute` — principal leg,
/// attestation spend, exposure release and lifecycle transition included. The sentence
/// above about the coupling being "removed" was therefore true of a controller pause
/// and false of a token pause. `mintableHeadroom()` now reads BOTH.
/// - THE OTHER MINT. R17 stated here that "`WaterfallEngine.fund`'s origination-fee mint
/// still reverts under a pause, which is intended". R18 CLAMPS that mint to
/// `mintableHeadroom()` as well, so under either pause `fund` now WITHHOLDS the fee and
/// the facility funds. That is deliberate and is not a weakening: stopping origination
/// during an emergency is the job of `WaterfallEngine`'s OWN `whenNotPaused` on `fund`,
/// which a guardian pausing the engine still gets in full. A CONTROLLER pause is a rule
/// about SUPPLY EXPANSION, and the fee is the part of `fund` that expands supply — so
/// withholding the fee is exactly what a controller pause should buy, and reverting the
/// whole origination was collateral damage of the same shape as the repayment coupling
/// this paragraph was written to remove.
function pause() external onlyRole(Roles.GUARDIAN_ROLE) {
_requireSettledState();
_pause();
}
/// @notice Unpauses mint/redeem and the yield mint.
function unpause() external onlyRole(Roles.GUARDIAN_ROLE) {
_requireSettledState();
_unpause();
}
// ── Views ────────────────────────────────────────────────────────────
/// @inheritdoc IMintRedeemController
function backingValue() public view returns (uint256) {
return _storage().reserves.totalBackingValue();
}
/// @notice Current economic USDfr supply, including earned claims after accrual opt-in.
/// @dev Uses the reserve's capped accounting and its frozen delivery snapshot. Read
/// USDfr.totalSupply() when measuring only physical token issuance.
function totalUSDfr() public view returns (uint256) {
return _effectiveSupply(_storage());
}
/// @notice Binds continuous accounting after reserve identities and the token's binding are configured.
/// @dev Binding is permanent; enabling the reserve itself is a separate guarded ceremony step.
function enableContinuousAccrual() external onlyRole(DEFAULT_ADMIN_ROLE) nonReentrant {
ControllerStorage storage $ = _storage();
if (address($.accrual) != address(0)) revert Controller_AccrualAlreadyBound();
if ($.pairedYieldCaller != address(0)) revert Controller_AccrualDuringPairedYield();
ControllerAccrualLib.validate(address($.reserves), address($.usdfr));
$.accrual = IContinuousAccrual(address($.reserves));
emit ContinuousAccrualBound(address($.reserves));
}
/// @notice The configured continuous reserve, or zero before explicit binding.
function accrualReserve() external view returns (address) {
return address(_storage().accrual);
}
/// @notice Converts a reserve-owned, already accrued liability into physical USDfr.
/// @dev Remains available while paused; all ordinary supply expansion keeps its pause gates.
function mintAccrued(uint256 nonce) external nonReentrant {
ControllerStorage storage $ = _storage();
if ($.pairedYieldCaller != address(0)) revert Controller_AccrualDuringPairedYield();
ControllerAccrualLib.deliver(address($.accrual), address($.usdfr), $.yieldSink, nonce);
emit AccruedDeliveryRelayed(nonce);
}
/// @inheritdoc IMintRedeemController
/// @dev AUDIT NOTE (MA-2/R18 MERGE ADJUDICATION). This is a compatibility diagnostic for the
/// RECORDED ledger; it is NOT an operation-admission predicate. The earlier MA-2 fix used
/// this absolute level as `WaterfallEngine.distribute`'s closing gate. That correctly
/// separated custody observation from recorded accounting, but deadlocked principal
/// recoveries whenever any genuine impairment or residual deficit remained.
///
/// `WaterfallEngine.distribute` now snapshots `recognizedDeficit()` and rejects only an
/// increase, after `ReserveManager.recordPayment` has independently proved exact cash
/// receipt. This view remains useful for comparing recorded and recognised bases, but a
/// false result does not forbid a non-worsening cash-in operation and a true result is not
/// sufficient authorization for one.
///
/// WHY THE RECORDED BASIS IS CORRECT HERE, AND IS NOT A HOLE. `distribute` is a cash-IN
/// path: `ReserveManager.recordPayment` pulls the borrower's USDC in and verifies receipt
/// by balance delta, so a distribution cannot lower live custody and cannot widen the
/// recognised gap (`Fix_MA02-recognition-contamination.t.sol
/// ::test_MA2_interestIsWithheldToRepairRecognisedGapWithoutBlockingRepayment` and
/// `::test_MA2_absorbedCustodyDeficitDoesNotBlockNeutralPrincipalCollection` — CITATION
/// CORRECTED, SWEEP-1 VAC-F8: the superseded name
/// `test_MA2_theInterestMintCannotWidenTheRecognisedGap` is not in the tree). Gating it
/// on the RECOGNISED
/// basis halted every performing borrower's repayment, protocol-wide, for a custody hole
/// elsewhere — blocking the money that repairs the balance sheet. The custody window is
/// closed where cash LEAVES: `_requireCustodiedReserve` (user par),
/// `ReserveStorageLib.requireIdleFullyCustodied` (both reserve out-doors, MA-1) and
/// `ReserveManager.custodyLossUnabsorbed()` (curator, R6-CF1).
///
/// DO NOT WIRE THIS INTO A USER path, dashboard, or absolute credit gate. It is
/// deliberately blind to the custody shortfall; using it as a solvency or exit-pricing
/// signal reinstates R4-01.
/// AUDIT FIX (SWEEP-3 S3-F1) — THE `_requireSettledState()` BELOW IS LOAD-BEARING, DO NOT
/// DELETE. `_requireSettledState`'s own NatSpec states the rule categorically: the RAW
/// delegating views are deliberately ungated because each is a single live read of one
/// module, and "what is false mid-transition is the COMPOSITION of a supply reading with a
/// backing reading ... so it is exactly the COMPOSITES that are gated". This is a
/// composite (`totalUSDfr() <= backingValue()`) and it was the one the R18 fix's
/// hand-written five-view enumeration missed — the sixth. MEASURED: it answered TRUE
/// ("supply is within backing") from inside the burn window on a book that was short both
/// before and after the transaction, while `backingInvariantHolds()` — the identical
/// composition one basis over — correctly REFUSED from the same frame.
/// Falsified by `test_S3_F1_creditServicingBackingHoldsAnswersFromInsideTheBurnWindow`.
function creditServicingBackingHolds() external view returns (bool) {
_requireSettledState();
return totalUSDfr() <= backingValue();
}
/// @inheritdoc IMintRedeemController
/// @dev AUDIT FIX (R4-01) — LOAD-BEARING, DO NOT "RESTORE" THIS TO `backingValue()`. This is
/// the protocol's public honesty surface: the dashboard reads it and the invariant
/// campaigns use it as the "is the protocol whole" predicate. Measured against the
/// RECORDED ledger it reported TRUE while `observeIdleUSDC()` was simultaneously
/// publishing a non-zero shortfall to the same caller in the same block — the contract
/// contradicting itself. It is now measured against `recognizedBackingValue()`.
/// @dev AUDIT NOTE (R16-M4): `WaterfallEngine.distribute` no longer HARD-GATES on this. It
/// gates on `recognizedDeficit()` not increasing across the call, which is the same
/// recognition-aware measurement expressed as a non-worsening rule, so a repayment that
/// REPAIRS backing is no longer refused merely because the protocol was already short.
/// @dev AUDIT FIX (R18): guarded by `_requireSettledState`. See
/// `Controller_ViewUnavailableMidTransition`.
function backingInvariantHolds() external view returns (bool) {
_requireSettledState();
return totalUSDfr() <= recognizedBackingValue();
}
/// @inheritdoc IMintRedeemController
function recognizedBackingValue() public view returns (uint256) {
return _storage().reserves.recognizedBackingValue();
}
/// @inheritdoc IMintRedeemController
/// @dev AUDIT FIX (R18): guarded by `_requireSettledState` — a composite of a supply reading
/// and a backing reading is false mid-burn. See `Controller_ViewUnavailableMidTransition`.
function backingDeficit() public view returns (uint256) {
_requireSettledState();
uint256 supply = totalUSDfr();
uint256 backing = backingValue();
return supply > backing ? supply - backing : 0;
}
/// @inheritdoc IMintRedeemController
/// @dev AUDIT FIX (R18): guarded by `_requireSettledState`, as `backingDeficit` is.
function recognizedDeficit() external view returns (uint256) {
_requireSettledState();
uint256 supply = totalUSDfr();
uint256 backing = recognizedBackingValue();
return supply > backing ? supply - backing : 0;
}
/// @inheritdoc IMintRedeemController
/// @dev THREE CORRECTIONS, ALL LOAD-BEARING (AUDIT FIX R17). This one view decides how much
/// interest `WaterfallEngine._routeInterest` may mint as yield, so every basis error in
/// it is paid out of the reserve and cannot be recovered.
///
/// (1) IT READS THE RECOGNISED BASIS, NOT THE RECORDED ONE. DO NOT "RESTORE" THIS TO
/// `backingValue()`. It is the headroom for MINTING, and minting against cash the reserve
/// can already see it does not hold is precisely what R4-01 forbids. Measured on the
/// recorded ledger, an unreconciled custody shortfall was invisible here: headroom
/// equalled the whole interest receipt, `_routeInterest`'s clamp withheld ZERO, the
/// protocol fee was taken on the GROSS out of an open hole (contradicting that function's
/// own "Forest Road does not collect a performance fee out of a shortfall"), and
/// `distribute`'s closing gate passed because the incoming cash and the new supply cancel
/// to the wei on both bases. Meanwhile `mint` and `redeem` were frozen and
/// `backingInvariantHolds()` published FALSE — the contract contradicting itself, which is
/// the R4-01 finding verbatim. In the healthy state `idleCustodyShortfall() == 0` makes
/// the two bases identical, so this is a STRICT TIGHTENING: headroom can only shrink,
/// withholding can only increase, and the healthy path is bit-for-bit unchanged.
///
/// (2) IT IS ZERO WHILE PAUSED. See `pause`. This is what lets `mintYield` keep
/// `whenNotPaused` — an absolute rule about supply expansion — without a guardian key
/// being able to stop every borrower repayment as a side effect.
///
/// (3) IT NETS OUT `seniorSubParShortfall()`. See that function. Without this, value
/// recovered from a released impairment mark becomes yield to the `sUSDfr` vault instead
/// of coverage for the holders who bore the mark.
///
/// (4) IT IS ZERO WHILE THE USDfr TOKEN IS PAUSED, NOT ONLY WHILE THIS CONTRACT IS
/// (AUDIT FIX R18) — DO NOT DELETE THE `$.usdfr.paused()` TERM. R17 shipped (2) reading
/// only `paused()`, this contract's own Pausable. The SAME guardian address holds
/// `GUARDIAN_ROLE` on `USDfr` (`Deploy.s.sol` grants both), and `USDfr._update` refuses
/// every mint while the token is paused — its protocol-leg carve-out requires
/// `from != address(0)`, which a mint can never satisfy. So one un-timelocked
/// `USDfr.pause()` still made `mintYield` REVERT, and `WaterfallEngine.distribute` is
/// atomic, so it took every borrower repayment down with it: principal leg, attestation
/// spend, exposure release, lifecycle transition. The clamp built to prevent exactly that
/// harm could not see the pause that caused it. Both pauses now read zero here, so either
/// one WITHHOLDS instead of reverting.
///
/// The four compose as a floor: whichever binds hardest wins, and each only ever
/// REDUCES what may be minted, so none of them can create an over-issuance.
/// @dev AUDIT FIX (R18): guarded by `_requireSettledState`. See
/// `Controller_ViewUnavailableMidTransition` — mid-burn this view read the ENTIRE realised
/// loss of a cascade as distributable yield capacity, and it is the exact quantity
/// `WaterfallEngine._routeInterest` sizes real yield off.
function mintableHeadroom() external view returns (uint256) {
_requireSettledState();
ControllerStorage storage $ = _storage();
// THE SAME THIRD SURFACE AS `previewRedeem` (Cantina 3.1.3). Advertising headroom while
// the reserve is paused publishes a mint that cannot execute: `mint` reaches
// `reserves.depositUSDC`, which is `whenNotPaused` on the reserve.
if (!_accrualAvailable($) || paused() || $.usdfr.paused() || IPausableModule(address($.reserves)).paused()) {
return 0;
}
uint256 backing = $.reserves.recognizedBackingValue();
// AUDIT FIX (ADR-0034 Y-bis) — `exitPrepaidAbsorption()` IS RETAINED ALONGSIDE
// `subParShortfall`, AND DELETING IT REOPENS THE LEAK ON THE JUNIOR SIDE. The junior draw
// burns junior USDfr against a mark (`recognizePrincipalImpairment`) that is CONSERVATIVE
// and REVERSIBLE. If the mark is later released, backing rises while supply is already
// lower by the drawn amount, so the book carries a surplus of exactly the standing
// prepayment. Untreated, this view reads that surplus as distributable and
// `WaterfallEngine._routeInterest` mints it to the `sUSDfr` vault as yield — the curator's
// crystallised loss becomes the senior's income. That is the identical leak R17's
// `seniorSubParShortfall` closed for the EXITER's haircut, aimed at the junior tranche
// instead. Retained, not recycled.
//
// IT IS A STOCK NETTED OFF A LEVEL, exactly like `subParShortfall` beside it, and NOT a
// cumulative stock differenced against a per-transaction flow — the shape that broke an
// adjacent fix on this same view.
//
// WHAT IT DOES NOT DO, SAID PLAINLY: there is no restitution path. A fully reversed mark
// leaves the curator permanently down and the value parked in this retention. Minting it
// back needs `CuratorModule` as a yield sink and a reversal of the per-pool share
// arithmetic. OUTSTANDING, and named as such.
//
// SWEEP-2 S2-F3 — OPEN, AND DELIBERATELY NOT FIXED IN THIS ROUND. STOPPED FOR A FOREST ROAD
// DECISION. The ledger has exactly TWO consumers: `realizeLoss`'s layer-0 credit
// (`ReserveManager.consumeExitPrepayment`, bounded by the facility's RECOGNISED MARK) and
// this netting. On an UNMARKED deficit — an idle write-down, a custody-reconciliation
// residual — the first has no route to fire (`totalPrincipalImpairment() == 0`, so the
// layer-0 credit is 0 and ReserveManager's live custody cascade deliberately does not
// consume the ledger, correctly avoiding a double charge), so the retention here stands
// forever and the book closes permanently over-backed by exactly the junior capital the
// exit burned. MEASURED: a
// 9,900.99e18 draw, a par settlement, `seniorSubParShortfall() == 0`, and
// `mintableHeadroom() == 0` for good.
//
// WHY IT IS NOT REMEDIATED HERE. Every available cure is an ECONOMIC choice under
// CLAUDE.md §0.7 and prime directive 5, not a safety fix:
// (a) retiring the ledger releases the surplus into `_routeInterest` — i.e. junior
// crystallised capital becomes SENIOR YIELD, which is the exact leak this term was
// added to close, merely on a different trigger;
// (b) refunding the curator needs `CuratorModule` as a yield sink plus a reversal of the
// per-pool share arithmetic — a new mechanism, not an audit-round edit;
// (c) leaving it is what ships today: the junior tranche's payment is retained as
// over-collateralisation for the remaining USDfr holders, and the withholding is on
// the SENIOR YIELD LEG, not a second charge on the junior tranche.
// Bounding it by `totalPrincipalImpairment()` was evaluated and REJECTED: it releases the
// surplus at the exact moment a mark is RELEASED, which is when the leak (a) actually
// fires. Forest Road must choose between (a), (b) and (c); do not choose it in code.
uint256 claimed = _effectiveSupply($) + $.subParShortfall + $.reserves.exitPrepaidAbsorption();
return backing > claimed ? backing - claimed : 0;
}
/// @inheritdoc IMintRedeemController
/// @dev THE CRYSTALLISED SENIOR HAIRCUT (AUDIT FIX R17) — DO NOT DELETE, AND DO NOT ADD A
/// SETTER THAT LOWERS IT.
///
/// THE PROBLEM IT ANSWERS. `ReserveManager.recognizePrincipalImpairment` is a governance
/// VALUATION act, and a REVERSIBLE one: `releasePrincipalImpairment` exists precisely
/// because, as its own NatSpec says, an irreversible mark "would be a one-way ratchet …
/// and governance would rationally refuse to mark at all". R16 made that reversible mark
/// PRICE-EFFECTIVE for exits the instant it lands. A holder who redeemed during the
/// window crystallised a PERMANENT loss against a TEMPORARY number; when the mark was
/// later released, the recovered value reappeared as headroom and `_routeInterest` minted
/// it to the `sUSDfr` vault. The senior exiter's haircut became someone else's yield —
/// and it did so before the §1.3 cascade's layers 1 and 2 (curator first-loss, `sGROVE`
/// backstop) had absorbed anything, which is the ordering `DefaultManager.realizeLoss`
/// refuses to invert (it reverts with `DefaultManager_LossExceedsAbsorptionCapacity`
/// rather than let a loss reach unstaked USDfr holders).
///
/// WHAT THIS DOES. Every sub-par settlement adds `usdfrIn - usdcOut * SCALE` here, and
/// `mintableHeadroom()` subtracts the running total. Recovered value therefore stays in
/// the pool as COVERAGE for the holders who are still in it, rather than being minted out
/// as yield. It is monotonic and has no setter on purpose: a governance lever that could
/// lower it would restore the leak in one transaction.
///
/// WHAT THIS DOES NOT DO, SAID PLAINLY. It does not REPAY the exiter — there is no
/// on-chain record of who exited at what price beyond the `SubParRedemption` and
/// `SeniorShortfallCrystallised` events, and building a claims register for departed
/// holders is a materially larger design than an audit round should introduce
/// unilaterally. It converts "the haircut is captured by the yield layer" into "the
/// haircut is retained by the remaining USDfr holders as over-collateralisation".
///
/// WHAT IT COSTS — R18 REWROTE THIS, BECAUSE R17'S VERSION UNDERSTATED IT AND ITS STATED
/// CURE WAS CIRCULAR. R17 said "the cost is bounded and one-off: interest is withheld
/// until backing exceeds supply plus this total, after which yield flows normally
/// forever". Three things were wrong with that sentence and an auditor must have the
/// correct ones:
/// 1. IT IS NOT ONLY INTEREST. `mintYield` enforces the retention as an ABSOLUTE level
/// check, so ORIGINATION FEES are refused by it too — and under R17 that refused
/// `WaterfallEngine.fund` OUTRIGHT, because `fund`'s fee mint was the one `mintYield`
/// caller not sized off `mintableHeadroom()`.
/// 2. THE CURE WAS CIRCULAR, WHICH IS FINDING M5's SHAPE. Withheld interest requires a
/// performing facility; a new facility requires `fund`; `fund` was refused. After a
/// terminal workout — the residual absorbed by the cascade, `deployedPrincipal() == 0`,
/// nothing left to release — nothing on chain could pay interest, so "after which
/// yield flows normally forever" had no "after which". R18 CLOSES THAT: `fund` now
/// clamps its fee to `mintableHeadroom()` and WITHHOLDS instead of reverting, so
/// origination stays open and its interest is once again a reachable cure. The
/// retention itself is unchanged.
/// 3. THE QUANTITY IS THE WHOLE LOSS, NOT THE HAIRCUT ALONE. Yield resumes only once
/// `recognizedBackingValue() - totalUSDfr() >= seniorSubParShortfall()`, i.e. the
/// protocol must earn back the standing deficit AND this retention out of interest.
/// The remaining cures, stated so an operator can act on them: withheld interest from any
/// performing facility, `ReserveManager.releasePrincipalImpairment` on a still-REVERSIBLE
/// mark, and `WaterfallEngine.setOriginationFee(classId, 0)` (DEFAULT_ADMIN, timelocked)
/// which removes the fee mint from `fund` altogether.
///
/// THE KNOWN OVER-CHARGE, DISCLOSED RATHER THAN FIXED. The justification above is that
/// value RECOVERED when a REVERSIBLE mark is released must stay with the holders who bore
/// it. This code cannot distinguish a mark that will be released from one that becomes a
/// REALISED loss, and accrues in both cases. On the realised path there is nothing left to
/// recover — curator first-loss, the sGROVE backstop and the senior vault have already
/// paid, and the exiter already bore their own haircut — so the retention keeps standing
/// against a recovery that can never arrive. The alternative named at the end of this
/// paragraph in R17 (a REALISED-LOSS WATERMARK: hold the crystallised amount pending and
/// retire it when the cascade allocates the corresponding loss) is the right answer to
/// that and is NOT implemented here: retiring retention on a `burnLoss` requires the
/// controller to know which burns correspond to which crystallisation, which is a
/// `DefaultManager` coordination change, and it would make this quantity non-monotonic —
/// the property the whole mitigation rests on. R18's clamp removes the ORIGINATION FREEZE
/// that made the over-charge severe; the over-charge itself is OUTSTANDING and is a Forest
/// Road decision on the brief's Part 4 locked economics (CLAUDE.md §0.5/§0.7), alongside
/// ADR-0034 (see `_redeem`), which decides the adjacent question of the exit PRICE.
function seniorSubParShortfall() external view returns (uint256) {
return _storage().subParShortfall;
}
/// @inheritdoc IMintRedeemController
/// @dev THE DUST FLOOR (finding R16-L3), STATED HONESTLY RATHER THAN "FIXED". USDfr worth
/// less than one whole USDC unit cannot be redeemed, because USDC has six decimals and
/// there is no such thing as a fraction of a unit to pay out. That is a property of the
/// SETTLEMENT ASSET, not a lock: the residue is at most 1e-6 USD, USDfr is freely
/// transferable so it aggregates, and the alternatives are worse — rounding UP pays out
/// cash that is not backed, and a dust ledger adds storage and a claim mechanism for
/// sub-cent amounts. What was genuinely wrong was that the threshold was invisible and
/// is no longer a constant: under sub-par pricing a holder needs
/// `ceil(1e12 * supply / backing)`, rounded up to the whole-USDC grid, before anything
/// is payable. This view publishes the exact quote so the frontend can state the floor
/// rather than discovering it by simulating a revert. It does NOT promise that a
/// redemption is available — see the R18 paragraph below.
///
/// @dev IT PRICES ON THE RECOGNISED BASIS (AUDIT FIX R17) — DO NOT "ALIGN" IT WITH `redeem` BY
/// MOVING IT BACK TO `totalBackingValue()`. R16 wrote that this view "shares `_quoteRedeem`
/// with `redeem`, so the two can never disagree". They share the ARITHMETIC; they do not
/// share the PRECONDITIONS, and that is the whole point. `redeem` sits behind
/// `_requireCustodiedReserve`, which guarantees the recorded and recognised bases are
/// equal by the time it quotes. This view sits behind nothing — it is permissionless and
/// needs no KYC — so on the recorded basis it published a PAR quote in exactly the state
/// where the recorded ledger is known to be false, for a call that would then revert
/// `Controller_ReserveCustodyShortfall`. That is R4-01 restated on a newer surface: the
/// contract contradicting itself in one block. On the recognised basis it now answers the
/// honest number, and wherever `redeem` is actually REACHABLE the two bases are identical
/// so the quote is still exact.
///
/// IT STILL IS NOT A PROMISE ACROSS TRANSACTIONS. The quote is valid for the state it was
/// read in and nothing more; `recordPrincipalWritedown` and friends can move it in the
/// next block, or the same one. The binding surface is `redeem`'s `minUsdcOut`, which is
/// what this number should be passed back into.
///
/// AN EMPTY PROTOCOL QUOTES NOTHING. With `supply == 0` the `backing >= supply` branch is
/// `0 >= 0`, so R16 quoted PAR for supply that does not exist. `_quoteRedeem` now returns
/// `(0, 0)`, which is also what makes its division provably safe.
///
/// @dev A CLOSED REDEMPTION QUOTES NOTHING EITHER (AUDIT FIX R18) — DO NOT DELETE THE CUSTODY
/// GATE. R17 changed WHICH number this published over a custody hole; it did not change
/// WHETHER one was published. In the standing R4-01 state — `idleCustodyShortfall() != 0`,
/// `backingInvariantHolds()` already FALSE — this view returned a full, honest-looking,
/// settleable quote for a call that `_requireCustodiedReserve` then refuses with
/// `Controller_ReserveCustodyShortfall`. Passing that very number back in as `minUsdcOut`,
/// as both NatSpecs direct, reverted. The window was wider than the sub-par case: wherever
/// recognised backing still exceeded supply it quoted full PAR for a call that cannot
/// execute. It now answers `(0, 0)`, which is already this view's documented way of saying
/// "nothing is payable", and the two surfaces agree in every state.
///
/// CONSEQUENCE FOR THE BASIS READ BELOW, STATED HONESTLY PER FINDING M6. With this gate in
/// place `recognizedBackingValue() == totalBackingValue()` at that line by construction —
/// the custody shortfall is the ONLY thing that separates the two bases — so the choice of
/// basis here is NO LONGER A FALSIFIABLE GUARD. It is kept, not deleted, because it is the
/// safe one if the gate is ever relaxed, and because it makes the intent legible. Read it
/// as belt-and-braces, exactly as `mint`'s `forceApprove(…, 0)` is read, and do not write a
/// comment claiming a mutation reds it.
function previewRedeem(uint256 usdfrAmount) external view returns (uint256 usdcOut, uint256 usdfrIn) {
_requireSettledState();
ControllerStorage storage $ = _storage();
// ── AUDIT FIX (SWEEP-3 S3-F3) — READ THE PAUSES, EXACTLY AS `mintableHeadroom()` DOES ───
// LOAD-BEARING, DO NOT DELETE. R18 finding (G) is "previewRedeem QUOTED A SETTLEABLE PRICE
// FOR A CALL THAT CANNOT EXECUTE", and its fix claimed "the two surfaces agree in every
// state". They did not agree under EITHER pause — the axis R18 finding (B) spent its whole
// effort teaching `mintableHeadroom()` to read. MEASURED: a full 400e6 USDC quote published
// while `redeem` reverts `EnforcedPause`, and again while the USDfr token pause closes the
// burn in `_update`. Direction is safe (the quote is too HIGH, so passing it back as
// `minUsdcOut` can only revert on a pause that would have reverted anyway), which is why
// this is LOW — it is a self-contradiction-in-one-block of the class R4-01 established, not
// a value defect. Falsified by
// `test_S3_F3_previewRedeemQuotesAFullPriceWhileRedemptionIsPaused` and
// `test_S3_F3b_previewRedeemQuotesAFullPriceWhileTheTokenPauseClosesTheBurn`.
// CANTINA 3.1.3, CLOSED 2026-09-09 and already closed on the BSC instance. The block above
// reads the controller and token pauses; the RESERVE is the third sibling of that family
// and was missed, so this could publish a full price for a redemption whose every release
// is `whenNotPaused`. ADR-0034 section W deferred it to "the next controller upgrade" and
// told integrators to read `ReserveManager.paused()` alongside the quote meanwhile. The
// mechanical reason the sibling fix missed it is that `ReserveManager` inherits `paused()`
// from `PausableUpgradeable` and never declares it on its own interface, so nothing in the
// type system pointed at it; `IPausableModule` is that pointer.
if (!_accrualAvailable($) || paused() || $.usdfr.paused() || IPausableModule(address($.reserves)).paused()) {
return (0, 0);
}
if ($.reserves.idleCustodyShortfall() != 0) return (0, 0);
// IT QUOTES THE UNDRAWN FLOOR, AND THAT IS A NAMED, DELIBERATE GAP (ADR-0034 Y-bis).
// `drawn = 0` here, so below par this view publishes the GROSS-marked price while `redeem`
// settles at the junior-drawn price — which is equal or BETTER, never worse. The direction
// is what makes it safe: passing this number back as `minUsdcOut`, exactly as this view's
// NatSpec directs, can never revert on slippage.
//
// WHY IT IS NOT SIMULATED. Simulating the draw needs live junior capacity — the five
// curator pools plus the shared sGROVE reserve. Neither is reachable from this contract
// (it holds no reference to `CuratorModule` or `SGrove`), and
// publishing it from `DefaultManager` measured 218 bytes in a contract that has 183 left
// after this change. ADR-0034 Y names `previewRedeem` alongside `redeem`, so this is
// recorded as OUTSTANDING rather than closed: the dashboard understates the exit price
// whenever junior capital stands behind it.
(usdcOut, usdfrIn) = _quoteRedeem(usdfrAmount, _effectiveSupply($), $.reserves.recognizedBackingValue(), 0);
// Suspend advisory quotes while an unratified arm stands. Direct exits wait
// for resolution regardless of the amount of available junior capital.
if (_unratifiedArm($) != 0) return (0, 0);
return (usdcOut, usdfrIn);
}
/// @inheritdoc IMintRedeemController
function isYieldSink(address account) external view returns (bool) {
return _storage().yieldSink[account];
}
/// @inheritdoc IMintRedeemController
function isLossSource(address account) external view returns (bool) {
return _storage().lossSource[account];
}
/// @notice Wired module addresses (for post-deploy validation and the dashboard).
function modules() external view returns (address usdfr, address compliance, address reserves) {
ControllerStorage storage $ = _storage();
return (address($.usdfr), address($.compliance), address($.reserves));
}
// ── Internals ────────────────────────────────────────────────────────
function _requireKYC(ControllerStorage storage $, address account) private view {
if (!$.compliance.isAllowed(account)) revert Controller_NotKYCAllowed(account);
}
/// @dev AUDIT FIX (R18) — LOAD-BEARING, DO NOT DELETE FROM ANY VIEW THAT CARRIES IT. The
/// READ-ONLY-REENTRANCY GUARD on the composite views.
///
/// THE WINDOW IS THE PROTOCOL'S OWN DESIGNED CALLBACK, NOT AN EXOTIC ONE. `_redeem` burns
/// (supply down) BEFORE `releaseUSDC` lowers backing, and `DefaultManager.realizeLoss`
/// burns both junior layers and the senior vault BEFORE `recordPrincipalWritedown` lowers
/// backing. `USDfr._update` fires the participation-points hook inside every one of those
/// burns. The R18 adversarial round measured an observer holding control there reading
/// `mintableHeadroom()` as the ENTIRE realised loss of a cascade — 400,000e18 of phantom
/// yield capacity, where the view reads 0 on both sides of the transaction —
/// `backingInvariantHolds()` as TRUE on a 20%-short book, and `previewRedeem` as PAR on
/// the same book. `mintableHeadroom()` is the exact quantity
/// `WaterfallEngine._routeInterest` sizes real yield off.
///
/// WHY REVERT RATHER THAN RETURN A NUMBER. R4-01's standard, which this file invokes
/// repeatedly, is that the contract must not contradict itself inside one block;
/// `backingInvariantHolds()`'s own NatSpec cites exactly that. Answering with a number
/// known to be false is the contradiction. A named revert is the honest answer and is
/// fail-CLOSED for an integrator: a `try/catch` reader sees "unavailable", never a lie.
/// The WRITE half was already closed — every entry point is `nonReentrant`, pinned by
/// `test_R17_G04_mintIsReentrancyLocked` and siblings — so this closes the read half with
/// the same slot and no new state.
///
/// THE RAW DELEGATING VIEWS (`backingValue`, `recognizedBackingValue`, `totalUSDfr`) ARE
/// DELIBERATELY NOT GATED. Each is a single live read of one module and is TRUE whenever it
/// is read — mid-transition included. What is false mid-transition is the COMPOSITION of a
/// supply reading with a backing reading taken at different points of the same state
/// change, so it is exactly the composites that are gated.
function _requireSettledState() private view {
if (_reentrancyGuardEntered()) revert Controller_ViewUnavailableMidTransition();
}
/// @dev AUDIT FIX (R4-01) — LOAD-BEARING GUARD, DO NOT DELETE. The USER paths are closed
/// while the reserve holds less USDC than its idle ledger claims. `observeIdleUSDC()`
/// published that gap to anyone for free; nothing consumed it, so `redeem` kept paying
/// 100 cents on the dollar to whoever arrived first until the live balance was gone.
///
/// SUB-PAR REDEMPTION DOES NOT REPLACE THIS AND MUST NOT BE ARGUED TO. Sub-par pricing
/// protects holders when the protocol KNOWS what it is worth. An unreconciled custody
/// gap is precisely the state in which it does NOT: `idleUSDCUnits` is a claim that has
/// been falsified by the live balance, so any quote derived from it would over-pay by
/// exactly the amount of the hole. Recognition (this) must come first; then
/// `reconcileIdleUSDC` writes the ledger down to the truth; THEN sub-par pricing is
/// meaningful and redemption reopens by itself.
///
/// WHY THIS IS NOT FOLDED INTO THE DEFICIT RULE, and must not be. The C-01 cascade's own
/// burn runs while this shortfall is standing: `ReserveManager.reconcileIdleUSDC`
/// allocates the loss and burns supply BEFORE it lowers `idleUSDCUnits`. A
/// recognition-aware assertion on the credit-layer paths would revert those burns and
/// brick custody-loss absorption entirely — the opposite of the intent. Recognition
/// closes the user window; absorption stays authenticated and unobstructed.
///
/// NOT A LATCH, and no role is needed to clear it: restoring custody, or the
/// authenticated `reconcileIdleUSDC` writing the ledger down to the live balance,
/// reopens mint and redeem in the same block with no governance action
/// (`test_R4_01_restoringCustodyReopensParBusinessWithNoGovernanceAction`).
function _requireCustodiedReserve(ControllerStorage storage $) private view {
uint256 shortfall = $.reserves.idleCustodyShortfall();
if (shortfall != 0) {
revert Controller_ReserveCustodyShortfall(shortfall, $.reserves.recognizedBackingValue());
}
}
/// @dev The one solvency measurement, read on the RECORDED basis. Deliberately NOT
/// recognition-aware — see `_requireCustodiedReserve` for why a recognition-aware
/// measurement on the supply-affecting paths would brick the C-01 absorption cascade,
/// and `ReserveManager`'s MERGE NOTE for why `totalBackingValue()` must stay recorded.
function _supplyAndBacking(ControllerStorage storage $) private view returns (uint256 supply, uint256 backing) {
supply = _effectiveSupply($);
backing = $.reserves.totalBackingValue();
}
function _effectiveSupply(ControllerStorage storage $) private view returns (uint256) {
return address($.accrual) == address(0)
? $.usdfr.totalSupply()
: ControllerAccrualLib.supply(address($.accrual), address($.usdfr));
}
function _requireAccrualFresh(ControllerStorage storage $) private view {
if (address($.accrual) != address(0)) $.accrual.requireAccrualFresh();
}
function _accrualAvailable(ControllerStorage storage $) private view returns (bool) {
return address($.accrual) == address(0) || ControllerAccrualLib.available(address($.accrual));
}
/// @dev THE SINGLE SOLVENCY RULE (ADR-0012 as amended by audit round R16 — findings
/// M3/M4/M5) — LOAD-BEARING, DO NOT DELETE FROM ANY CALL SITE. An operation may not
/// INCREASE `deficit = max(0, totalSupply - backingValue)`.
///
/// WHICH BASIS THIS MEASURES (R17 CORRECTION — R16 STATED THE RULE IN BASIS-FREE TERMS AN
/// AUDITOR WOULD READ AS COVERING BOTH). It measures the RECORDED deficit only. That is
/// correct for `mint` and `redeem`, which sit behind `_requireCustodiedReserve` and so
/// cannot execute at all while the two bases differ, and it is deliberate for `burnLoss`,
/// which carries no assertion because it can only lower supply. It was NOT sufficient for
/// `mintYield`, the one supply-EXPANDING path with no custody precondition, which is why
/// that path additionally asserts `_assertRecognizedDeficitNotWorsened`.
///
/// WHILE THE PROTOCOL IS WHOLE THIS IS ADR-0012, UNCHANGED. `deficitBefore == 0` forces
/// `deficitAfter == 0`, i.e. `totalSupply <= backingValue`, and it still reverts with
/// `Controller_BackingInvariantViolated(supply, backing)` — the same error, the same
/// arguments, the same meaning. Nothing about the healthy path is relaxed.
///
/// WHILE THE PROTOCOL IS SHORT IT IS THE RULE THE ABSOLUTE FORM COULD NOT EXPRESS. The
/// absolute form said only "supply exceeds backing", which is already true and stays
/// true, so it reverted every operation including the ones that repair the hole. The
/// distinct `Controller_DeficitWorsened` error exists so that a caller in this state is
/// told the operation was refused for WIDENING the gap, not that a gap exists — an
/// auditor or an integrator reading `Controller_BackingInvariantViolated` in a
/// knowingly sub-par protocol would reasonably conclude the check was firing for the
/// standing condition.
///
/// IT IS MEASURED, NOT ASSUMED — BUT IT IS A NON-WORSENING RULE, AND R18 CORRECTED WHAT
/// R17 CLAIMED THAT BUYS. Both readings do come from live external calls to the token and
/// the reserve, taken before and after the operation. R17 concluded from that: "a module
/// that reports one thing and does another is caught here even when the operation's own
/// arithmetic looks correct." THAT SENTENCE WAS FALSE WHENEVER THE PROTOCOL CARRIED
/// SURPLUS. The rule is non-worsening, so a discrepancy is caught only for the part
/// EXCEEDING `backingValue() - totalUSDfr()`; the standing surplus silently pays for the
/// rest. R17 made that worse rather than better, because `mintableHeadroom()` now nets out
/// `seniorSubParShortfall()` and `_routeInterest` therefore mints down to
/// `surplus == retention` rather than to zero — so after any crystallised haircut the
/// protocol is DESIGNED to sit permanently on a masking budget of exactly that size.
/// The correct statement is: this rule catches only the part of any discrepancy that
/// exceeds the standing surplus, and it is a BACKSTOP, not the primary measurement. The
/// primary measurements are the LEVEL-FREE DELTA CHECKS on the operations themselves —
/// `Controller_DepositNotCustodied` (custody), `Controller_DepositNotRecognized`
/// (recognition, added in R18 for exactly this reason) and
/// `Controller_RedemptionNotSettled` (outflow) — each of which is an EQUALITY on a measured
/// delta that no surplus can absorb.
function _assertDeficitNotWorsened(ControllerStorage storage $, uint256 supplyBefore, uint256 backingBefore)
private
view
{
(uint256 supplyAfter, uint256 backingAfter) = _supplyAndBacking($);
uint256 deficitAfter = supplyAfter > backingAfter ? supplyAfter - backingAfter : 0;
uint256 deficitBefore = supplyBefore > backingBefore ? supplyBefore - backingBefore : 0;
if (deficitAfter <= deficitBefore) return;
if (deficitBefore == 0) revert Controller_BackingInvariantViolated(supplyAfter, backingAfter);
revert Controller_DeficitWorsened(deficitBefore, deficitAfter);
}
/// @dev An unratified custody arm blocks every direct exit, independent of price
/// and junior capacity. Governed false-alarm cancellation preserves credit marks.
function _requireNoArmedExit(ControllerStorage storage $, uint256 usdcOut, uint256 usdfrIn)
private
view
{
uint256 armId = _unratifiedArm($);
if (armId != 0) revert Controller_ReserveLossArmFreeze(armId, usdcOut, usdfrIn);
}
/// @dev Only the incident belonging to this arm releases its additional restriction.
function _unratifiedArm(ControllerStorage storage $) private view returns (uint256 armId) {
uint256 armIncidentId;
(armId, armIncidentId,,) = $.reserves.reserveLossArm();
if (armId == 0) return 0;
(uint256 openIncidentId,) = $.reserves.activeReserveLossIncident();
if (openIncidentId == armIncidentId) return 0;
}
/// @dev The burn is rounded down to native units, then the payout is rounded down.
/// Actual junior delivery improves the settled price; the preview uses zero delivery.
/// Remaining holders retain any rounding difference. Empty supply quotes zero.
function _quoteRedeem(uint256 usdfrAmount, uint256 supply, uint256 backing, uint256 drawn)
private
pure
returns (uint256 usdcOut, uint256 usdfrIn)
{
if (supply == 0) return (0, 0);
usdfrIn = (usdfrAmount / SCALE) * SCALE;
// CANTINA 3.1.1, AND THE BSC INSTANCE ALREADY CARRIED THIS FIX. Bound the SUM rather than
// the addend: `usdfrIn + drawn` below overflowed on a max-sized input and the caller got a
// bare `Panic(0x11)` instead of a decodable error. `supply - drawn` is underflow-free
// because `drawn` was burned out of `supply`, and bounding against it makes the addition
// UNREPRESENTABLE rather than merely unlikely while refusing only inputs no holder can
// hold. It sits in the shared quote so `previewRedeem` and `_redeem` answer identically.
uint256 bound = supply - drawn;
if (usdfrIn > bound) revert Controller_RedeemExceedsSupply(usdfrIn, bound);
uint256 valueOut;
if (backing >= supply) {
valueOut = usdfrIn;
} else {
valueOut = Math.mulDiv(usdfrIn + drawn, backing, supply);
// THE PAR CEILING (ADR-0034 Y-bis). Stated honestly per finding M6's own rule: with
// `_exitDrawTarget`'s exact `ceil` sizing this is UNREACHABLE, and I could not
// construct a mutation that reds it without also breaking the sizing — so DO NOT write
// a comment claiming a mutation reds it. It is kept, not deleted, because it is the
// only thing standing between a future sizing bug and an exiting holder being paid
// ABOVE par out of first-loss capital, i.e. stealing the junior tranche through
// `redeem`. Read it exactly as `mint`'s `forceApprove(…, 0)` is read.
if (valueOut > usdfrIn) valueOut = usdfrIn;
}
usdcOut = valueOut / SCALE;
if (usdcOut == 0) usdfrIn = 0;
}
/// @dev ADR-0034 Y-bis — HOW MUCH JUNIOR CAPITAL THIS EXIT NEEDS. Pure so it can be reasoned
/// about and fuzzed on its own.
///
/// THE RULE. `d* = min( ceil(usdfrIn * D / B), D )` with `D = supply - backing`.
///
/// WHY `/B` AND NOT `/supply` — THIS IS THE WHOLE ARITHMETIC AND IT IS EASY TO GET WRONG.
/// Burning `d` of junior USDfr removes `d` from SUPPLY ONLY; backing does not move,
/// because junior capital is denominated in USDfr, not in the reserve's USDC. Requiring
/// that the holders who STAY are no worse off after the exit gives
/// `B(supply - d - u) <= supply(B - v)`, i.e. `v <= B(u + d)/supply`; setting `v = u`
/// (par) yields `d >= u * D / B`. A `u * D / supply` draw structurally UNDER-draws and
/// leaves the exiter impaired while junior capital sits intact — which is decision X's
/// defect, not its cure.
///
/// WHY IT CANNOT OVER-DRAW, WHICH IS ADR-0034's THIRD BINDING REQUIREMENT. Each draw
/// lowers supply by exactly `d` with backing unmoved, so `D' = D - d` EXACTLY, and the
/// exit itself lowers `D` by a further `u - v >= 0`. The stock therefore decrements by the
/// flow one-for-one and draws TELESCOPE: cumulative draw over any sequence of exits can
/// never exceed the `D` standing when the mark was taken.
///
/// THE `min(..., D)` CLAMP IS UNREACHABLE, AND THIS PARAGRAPH USED TO CLAIM OTHERWISE.
/// CORRECTED (SWEEP-3 S3-F4). It said the clamp "makes over-draw UNREPRESENTABLE rather
/// than merely bounded" and cited
/// `testFuzz_Y_G05_theDrawNeverExceedsTheStandingDeficit` as its falsifier. BOTH CLAIMS
/// WERE FALSE. MEASURED: neutralising the clamp so it still compiles and still reads both
/// operands leaves the ENTIRE non-fork suite byte-identical to baseline — including that
/// named fuzz test at 1,025 runs and the ADR-0034 Z certifier
/// `invariant_Z_noDrawExceedsTheStandingDeficit` at 256 runs x 32,768 calls. Zero catchers.
/// THE THEOREM, so nobody re-argues it: the clamp binds iff `ceil(u*D/B) > D`, i.e. iff
/// `u > B`. `drawn` is measured as a balance RISE on the source, so the tokens must arrive
/// from other USDfr balances: `drawn <= S - u - balBefore(source) <= S - u`. With
/// `u > B = S - D` that gives `drawn < D <= the clamped target`. The clamp can never change
/// `drawn` on any path, including against a lying source.
/// KEEP IT — it is the cheap, legible statement of the bound, exactly as the par ceiling in
/// `_quoteRedeem` is kept — but label it honestly, and DO NOT write a comment claiming a
/// mutation reds it.
///
/// WHY IT CANNOT UNDER-DRAW. The target rounds UP (`Ceil`); every other rounding in the
/// quote is DOWN. So R17's
/// `testFuzz_M3_aSubParExitNeverWorsensTheRatioForTheHoldersWhoStayed` property is
/// STRENGTHENED by this change, never weakened.
///
/// IT IS A FLOW COMPUTED FROM A STOCK, AND `pendingSeniorImpairment()` IS DELIBERATELY NOT
/// CONSULTED. That view is a CREDIT-layer stock in units of declared/past-due PRINCIPAL;
/// `D` is a CUSTODY/VALUATION quantity. They diverge in BOTH directions — a
/// `writeDownIdleUSDC` custody loss has `D > 0` with `pendingSeniorImpairment() == 0`, and
/// a declared-but-unmarked default has the reverse — so mixing them would either fail to
/// fund the exit at all or price a whole book sub-par. That mixing of a cumulative stock
/// into a per-transaction flow is precisely the shape that broke an adjacent
/// `mintableHeadroom()` fix.
function _exitDrawTarget(uint256 usdfrIn, uint256 supply, uint256 backing) private pure returns (uint256 target) {
if (usdfrIn == 0 || backing == 0 || backing >= supply) return 0;
uint256 deficit = supply - backing;
target = Math.mulDiv(usdfrIn, deficit, backing, Math.Rounding.Ceil);
if (target > deficit) target = deficit;
}
/// @dev ADR-0034 Y-bis — THE ATOMIC JUNIOR DRAW — LOAD-BEARING, DO NOT DELETE. Read
/// `ADR/0034-exit-pricing-in-cascade-order.md` in full before changing anything here.
///
/// WHAT IT FIXES. `_quoteRedeem` priced the direct exit off GROSS `totalBackingValue()`,
/// which nets NOTHING against junior capital, while the `sUSDfr` path prices off
/// `DefaultManager.pendingSeniorImpairment()`, which nets curator first-loss and then the
/// sGROVE backstop. A holder redeeming while curator capital sat intact therefore absorbed
/// a loss the junior tranche contracted to take first — the locked §1.3 cascade run
/// backwards. Forest Road (2026-08-08) decided the residual price and the draw are NOT
/// alternatives: the residual price PROMISES more than gross-marked backing, and the
/// difference sits in the curator pool and the backstop, not in the reserve's USDC. So
/// junior capital is drawn IN THIS TRANSACTION and cascade order is enforced AT
/// SETTLEMENT.
///
/// THE SOURCE IS DERIVED, NOT STORED, AND THAT IS DELIBERATE. `$.reserves.lossAbsorber()`
/// IS the cascade the protocol runs its losses through; `ReserveManager.setLossAbsorber`
/// already refuses any address whose `reserveLossSource()` does not point back at it. A
/// second stored pointer here would be a second source of truth that could DISAGREE — a
/// controller drawing from `DefaultManager` v1 while the reserve allocates losses through
/// v2 — and it would cost a namespaced tail field, a governance setter, an ACL-surface
/// re-pin and `Deploy`/`Validate`/`Handover` wiring to buy that risk. Deriving costs one
/// `staticcall` and cannot desynchronise.
///
/// THE BURN AUTHORISATION IS THE `lossSource` LIST, AND IT IS THE GUARD THAT MATTERS.
/// `$.usdfr.burn(source, drawn)` is raw MINTER_ROLE power over a third party's balance —
/// exactly the confiscation primitive R16-M1/M2 constrained. Requiring `source` to be a
/// governance-named loss source reuses that existing, already-deployed list rather than
/// inventing a parallel one, so a compromised or misconfigured `ReserveManager` can at
/// worst point this at an address that is not on the list — which REVERTS. It can never
/// make `redeem` burn a user's wallet. Falsified by
/// `test_Y_G02_theDrawRefusesASourceGovernanceHasNotNamedALossSource`.
///
/// IT BURNS IN PLACE RATHER THAN CALLING `burnLoss`. `burnLoss` is `nonReentrant` on THIS
/// contract and `redeem` already holds that lock, so the `DefaultManager.realizeLoss`
/// shape (draw, then call back into `burnLoss`) reverts with
/// `ReentrancyGuardReentrantCall`. The drawn USDfr is left standing at the source and
/// burned here. Anyone "restoring symmetry" with `realizeLoss` bricks every under-backed
/// exit.
///
/// MEASURE, DO NOT TRUST. The delivered amount is measured as a balance delta on the
/// SOURCE and must be AT LEAST what the source reported, and the report must be at most
/// what was requested. A source that over-reports, under-delivers, or hands back more than
/// asked can therefore only cause a REVERT, never an overpayment out of junior capital.
/// Falsified by `test_Y_G06_aLyingDrawSourceCanOnlyRevertTheExitNeverOverpayIt` (the
/// report/delivery legs) and by
/// `S2_GuardVacuity.t.sol::test_S2_anOverDeliveringDrawSourceMustStillBeRefused` (the
/// `reported > target` leg, which had NO falsifier in the tree until SWEEP-2 measured it
/// as a deletable guard).
///
/// AUDIT FIX (SWEEP-2 S2-F5): the delivery leg is a FLOOR, not an equality, because a
/// strict equality here is a redemption kill switch in the hands of the fail-open points
/// hook. The full finding is at the comparison itself — read it before touching this.
///
/// WHERE IT SITS IN `_redeem`, AND WHY IT MUST STAY THERE. It runs BEFORE the R18
/// `payeeBefore`/`payeeAfter` delivery window. The burn fires `USDfr`'s deliberately
/// FAIL-OPEN points hook and `CuratorModule` fires `IPointsModule.onCuratorLoss`, and
/// R18's general rule on `_redeem` is that no call a redeemer or a governance-set module
/// can influence may sit between `payeeBefore` and `payeeAfter`. DO NOT MOVE IT DOWN.
///
/// UNWIRED IS TOLERATED, AND ONLY BECAUSE IT IS SAFE. A zero `lossAbsorber()` draws
/// nothing and the exit settles at exactly today's gross price. That is the state every
/// deployment starts in, and refusing the exit there would be a fresh deadlock in the
/// state ADR-0034 exists to cure. `Validate.s.sol` asserts the production wiring.
///
/// NOT WIRED IS SAFE; WIRED-BUT-UNANSWERING IS NOT, AND THAT IS DELIBERATE. A source that
/// is present but cannot answer `drawForSeniorExit` reverts the exit rather than silently
/// pricing it at the gross mark. This follows the house rule `WaterfallEngine` states for
/// the same shape — optional wiring via a zero check, and NEVER `try/catch`, because "a
/// failure here must fail loudly" (CLAUDE.md prime directive 4). THE OPERATIONAL
/// CONSEQUENCE, STATED SO IT IS NOT DISCOVERED LATE: `DefaultManager` MUST BE UPGRADED
/// BEFORE THIS CONTROLLER. Upgrading the controller first leaves every UNDER-BACKED exit
/// reverting until the manager catches up. Par exits are unaffected in either order,
/// because no draw is attempted while `backing >= supply`.
///
/// SLITHER TRIAGE (CLAUDE.md §3.2 — transcribe into `STATE.md` at merge). This function
/// adds `reentrancy-balance` on itself and on `_redeem` (which goes 1 -> 3), plus
/// `incorrect-equality`. Both are the guard, not a bug, and are the same triage `mint` and
/// `_redeem` already carry: a balance read STRADDLING an external call and gating a state
/// change IS the measurement. AUDIT FIX (SWEEP-2 S2-F5) CORRECTS THIS PARAGRAPH: it used
/// to say the STRICT EQUALITY is what makes a lying source fail closed in both directions,
/// and that "a `>=` relaxation would let a source over-deliver and strand USDfr". Both
/// halves were wrong. The equality was breakable by any third party pushing one wei into
/// the window (measured), and over-delivery is refused by `reported > target`, not by the
/// delivery comparison at all — the source cannot over-deliver AND report honestly without
/// failing that first check, and if it under-reports its own over-delivery the excess is
/// simply never burned. A non-straddling read would still let it lie, which is why the
/// straddle stays.
/// `DefaultLossLib.coverFromBackstop` keeps the same straddling measurement for facility
/// defaults, senior exits and the retained compatibility entry. The live custody path
/// performs its equivalent balance-delta check inside `ReserveManager`; the extraction is
/// therefore a RENAME with no net new finding.
function _drawJuniorForExit(ControllerStorage storage $, uint256 usdfrIn, uint256 supply, uint256 backing)
private
returns (uint256 drawn)
{
uint256 target = _exitDrawTarget(usdfrIn, supply, backing);
if (target == 0) return 0;
address source = $.reserves.lossAbsorber();
if (source == address(0)) return 0;
if (!$.lossSource[source]) revert Controller_ExitDrawSourceNotAuthorised(source);
uint256 balBefore = $.usdfr.balanceOf(source);
uint256 reported = ISeniorExitDrawSource(source).drawForSeniorExit(target);
uint256 balAfter = $.usdfr.balanceOf(source);
uint256 delivered = balAfter < balBefore ? 0 : balAfter - balBefore;
// ── AUDIT FIX (SWEEP-2 S2-F5) — THE MEASUREMENT IS A FLOOR, NOT AN EQUALITY ──
//
// LOAD-BEARING IN BOTH DIRECTIONS. DO NOT RESTORE `drawn != reported || drawn > target`.
//
// WHY THE EQUALITY HAD TO GO. R18 found that `_redeem`'s outflow window contained a call
// the deliberately FAIL-OPEN points hook could influence, hoisted the burn out, and wrote a
// general rule into `_redeem`'s NatSpec: no call a redeemer or a governance-set module can
// influence may sit inside a strict-equality balance window. ADR-0034 Y-bis then opened a
// SECOND such window here. Everything inside `drawForSeniorExit` — `CuratorModule`'s USDfr
// transfer to `DefaultManager`, `SGrove.coverShortfall`'s — fires `USDfr._update`'s points
// hook, which is fail-open ONLY inside the token's own `try/catch`; a points module that
// succeeds while transferring ONE WEI of USDfr into `source` broke `delivered == reported`,
// and this revert is OUTSIDE that `try/catch`. MEASURED: `Controller_ExitDrawNotDelivered
// (target=4950...50, reported=4950...50, measured=4950...51)` — exactly one wei bricked
// EVERY under-backed exit, the one path ADR-0034 exists to keep open, and unwiring the
// module reopened it in the same state.
//
// WHAT IS STILL FAIL-CLOSED, AND WHY THAT IS THE WHOLE SAFETY PROPERTY:
// • `reported > target` -> REVERT. A source may never hand back more than it was asked
// for; ADR-0034 requirement 3 is that the draw brings absorption FORWARD in time, it
// does not ENLARGE it. This is also the disjunct SWEEP-2 M3 measured as unfalsifiable
// in its old `drawn > target` form (`LyingExitDrawSource` never moves a token, so both
// of its modes were caught by the equality alone). It now has a real falsifier:
// `S2_GuardVacuity.t.sol::test_S2_anOverDeliveringDrawSourceMustStillBeRefused`.
// • `delivered < reported` -> REVERT. A source that OVER-REPORTS or UNDER-DELIVERS still
// fails loudly, which is the house rule (CLAUDE.md prime directive 4) and the reason
// this is a measurement at all.
// Only a THIRD PARTY pushing EXTRA tokens into the source is now tolerated, and it is
// strictly harmless: `drawn` is set from `reported`, which is bounded by `target`, so the
// donation is neither burned nor credited to the redeemer's price. It simply sits at the
// loss absorber, exactly as an unsolicited transfer to any module does.
if (reported > target || delivered < reported) {
revert Controller_ExitDrawNotDelivered(target, reported, delivered);
}
drawn = reported;
if (drawn == 0) return 0;
$.usdfr.burn(source, drawn);
emit SeniorExitJuniorDrawn(msg.sender, target, drawn);
}
/// @dev A callback cannot replace the implementation or its authorities while a guarded
/// financial operation is using them. An idle controller remains governable when stale.
function _grantRole(bytes32 role, address account) internal override returns (bool) {
_requireSettledState();
return super._grantRole(role, account);
}
function _revokeRole(bytes32 role, address account) internal override returns (bool) {
_requireSettledState();
return super._revokeRole(role, account);
}
function _authorizeUpgrade(address) internal view override onlyRole(Roles.UPGRADER_ROLE) {
_requireSettledState();
}
/// @dev CANTINA 3.1.2. A module must be a contract, must not be a delegated EOA, and must
/// answer the view the controller will call on it.
///
/// EXACT CALLDATA, not a bare selector with a padded argument: solc's dispatcher ignores
/// trailing calldata, so a selector-plus-argument probe would silently succeed against a
/// no-argument view and prove less than it appears to. `staticcall` so a probe can never
/// mutate; the returned value is discarded because what is tested is that the call
/// SUCCEEDS and returns a word.
///
/// THE EIP-7702 LIMB WAS ADDED 2026-09-10, and it closes an inconsistency rather than a
/// new attack. `setLossSource` already refuses a delegated EOA through `_isDelegatedEOA`,
/// for the reason recorded at length above finding (C): since Pectra an ordinary
/// key-controlled EOA that has signed a `SetCode` authorization carries a 23-byte code
/// field, so `code.length == 0` stopped being a test for "is a contract". This probe was
/// still using the old test, so the same address the loss-source setter refuses could be
/// wired in as a module here. Two guards in one contract disagreeing about what counts as
/// a contract is the kind of gap an auditor is entitled to find embarrassing.
///
/// WHAT THIS STILL DOES NOT PROVE, stated because the previous version of this comment
/// claimed more than it delivered. A probe that only asks "does a staticcall return a
/// word" cannot distinguish a real module from an implementation reached instead of its
/// proxy, from an unrelated ERC-20 that happens to answer, or from a fallback sink that
/// returns 32 bytes for any selector. Those remain admissible and the controls for them
/// are elsewhere: timelocked `DEFAULT_ADMIN_ROLE` on every setter, and `Validate.s.sol`
/// asserting each wired address against the deployment manifest. Do not read this probe
/// as authentication; it is a liveness check that turns a silent misconfiguration into a
/// loud one.
function _requireModuleResponds(address module, bytes memory callData) private view {
if (module.code.length == 0 || _isDelegatedEOA(module)) revert Controller_ModuleNotResponding(module);
(bool ok, bytes memory data) = module.staticcall(callData);
if (!ok || data.length < 32) revert Controller_ModuleNotResponding(module);
}
function _storage() private pure returns (ControllerStorage storage $) {
assembly {
$.slot := CONTROLLER_STORAGE_LOCATION
}
}
}
src/interfaces/IAccrualLifecycle.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title IAccrualLifecycle
/// @notice Authenticated loan events consumed by the reserve's continuous accounting book.
/// @dev These methods accept no caller-selected accounting timestamp or interest correction.
interface IAccrualLifecycle {
/// @notice Supported forward fixed-rate terms, projected from a consumed bridge amendment.
struct Terms {
uint16 rateBps;
uint32 yearSeconds;
uint64 nextPaymentDue;
uint64 paymentInterval;
uint64 maturity;
}
/// @notice Prospective fixed Actual/360 terms for one concurrent cash/PIK facility.
struct MixedTerms {
uint16 cashRateBps;
uint16 pikRateBps;
uint32 yearSeconds;
uint64 nextPikCapitalization;
uint64 pikCapitalizationInterval;
uint64 maturity;
}
/// @notice Contractual debt, separately disclosed from the reserve's streamed accounting face.
struct Debt {
uint256 principal;
uint256 interest;
uint256 balanceCeiling;
uint64 accruedThrough;
uint64 nextCapitalization;
uint64 maturity;
bool pik;
bool active;
bool known;
}
/// @notice Current unpaid interest separated by its legal settlement leg.
/// @dev `mixed` distinguishes a concurrent facility from the equivalent balances on a
/// one-leg note. Unknown or disabled records return the all-zero shape.
struct InterestLegs {
uint256 cash;
uint256 pik;
uint64 accruedThrough;
bool mixed;
bool known;
}
/// @notice Registers the bound waterfall's just-funded, authenticated bridge facility.
function registerAccruingLoan(uint256 facilityId) external;
/// @notice Processes a bounded number of chronological due events; partial progress persists.
function checkpointAccrual(uint256 maximum) external returns (uint256 processed, bool fresh);
/// @notice Transfers one facility's existing virtual receivable into its native face ledger.
function postAccruedLoan(uint256 facilityId) external returns (uint256 amount);
/// @notice Applies the bridge's consumed, authenticated amendment prospectively.
function amendAccruingLoan(uint256 facilityId, Terms calldata terms) external;
/// @notice Applies the bridge's consumed, authenticated two-leg amendment prospectively.
function amendMixedAccruingLoan(uint256 facilityId, MixedTerms calldata terms) external;
/// @notice Aligns and permanently stops the facility before its default declaration snapshot.
function stopAccruingLoan(uint256 facilityId) external;
/// @notice Changes only the bound default manager's growing past-due cohort membership.
function setAccrualPastDue(uint256 facilityId, bool marked) external;
/// @notice Contractual debt through the capped, coherent portfolio frontier, in constant time.
function accruedDebt(uint256 facilityId) external view returns (Debt memory);
/// @notice Current cash-pay and PIK balances through the same coherent frontier, in constant time.
function accruedInterestLegs(uint256 facilityId) external view returns (InterestLegs memory);
/// @notice Additional unposted interest on a class's marked past-due cohort.
function accruedPastDue(uint256 classId) external view returns (uint256 amount);
/// @notice Streamed book face not yet posted for one facility; distinct from canonical interest.
function unpostedAccruedLoan(uint256 facilityId) external view returns (uint256 amount);
/// @notice Read at most 100 facility contributions through one coherent portfolio frontier.
/// @dev Values equal individual unpostedAccruedLoan reads in the supplied order, including duplicates.
function unpostedAccruedLoans(uint256[] calldata facilityIds) external view returns (uint256[] memory amounts);
}
/// @notice The reserve alone advances already signed PIK capitalization boundaries.
interface IAccrualBridge {
function setAccruedPaymentDue(uint256 facilityId, uint64 nextDue) external;
}
/// @notice Narrow notification of a posted receivable already counted in effective exposure.
interface IAccrualRegistry {
function recordAccruedExposure(uint256 classId, bytes32 borrowerId, bytes32 stateId, uint256 amount) external;
}
/// @notice Moves already-counted cohort growth into the default manager's recorded risk carrier.
interface IAccrualRisk {
function onAccrualPosted(uint256 facilityId, uint256 amount) external;
}
/// @notice The waterfall changes its standing interest fee only prospectively.
interface IAccrualFeeConfig {
function setAccrualFee(uint16 feeBps, address recipient) external;
}
/// @notice Constant-time servicing of signed dates with no positive queued accrual work.
interface IAccrualServicing {
function serviceAccruedLoan(uint256 facilityId) external returns (uint256 capitalized);
function accrualLoanScheduled(uint256 facilityId) external view returns (bool);
}
/// @notice Explicit native loss allocation of an independently derived sub-unit discrepancy.
interface IAccrualRounding {
/// @notice Monotone unabsorbed contractual rounding loss, never caller-selected debt relief.
function roundingLossUnabsorbed() external view returns (uint256);
/// @notice Controller-only consumption of one exact reserve-owned physical burn permit.
/// @dev Returns false outside a rounding continuation; normal loss admission then applies.
function consumeAccrualLossBurn(address caller, address from, uint256 amount) external returns (bool);
}
/// @notice The reserve reduces only a marked contribution whose face it has actually written down.
interface IAccrualRoundingRisk {
function onAccrualRounding(uint256 facilityId, uint256 amount) external;
}
/// @notice Registry continuation paired with a reserve-proved native rounding write-down.
interface IAccrualRoundingRegistry {
function recordAccruedWriteDown(uint256 classId, bytes32 borrowerId, bytes32 stateId, uint256 amount) external;
}
/// @notice Measured receipt settlement and terminal retirement, separately bound to servicing modules.
interface IAccrualReceipts {
/// @notice Measures an attested receipt and discharges separately tracked principal and interest.
function repayAccruingLoan(uint256 facilityId, address payer, uint256 principal, uint256 interest)
external
returns (uint256 outstanding);
/// @notice Releases a fully extinguished, resolved facility's active-book slot after its risk hooks.
function retireAccruedLoan(uint256 facilityId) external;
}
src/interfaces/IComplianceRegistry.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title IComplianceRegistry
/// @notice Compliance capability layer (ADR-0011, as amended by the 2026-07-14 directive):
/// a KYC allowlist consulted ONLY at the mint/redeem primary gate, and a narrow
/// sanctions blocklist consulted on transfers. The per-token transfer-allowlist
/// capability was removed — transfers are permissionless (sanctions-only). Policy
/// (who is eligible/sanctioned) is set by governance/counsel off this interface.
interface IComplianceRegistry {
/// @notice Emitted when an account's KYC allowlist status changes.
event AllowlistUpdated(address indexed account, bool allowed);
/// @notice Emitted when an account's sanctions/jurisdiction-block status changes.
event JurisdictionBlockUpdated(address indexed account, bool blocked);
/// @notice Timelocked governance changed an address's borrower-payout approval.
/// @dev This list is deliberately independent of the operational KYC allowlist.
event FundingRecipientApprovalUpdated(address indexed account, bool approved);
/// @notice True if `account` has passed KYC and may use the gated primary paths
/// (USDfr mint/redeem). Holding and transferring are permissionless.
function isAllowed(address account) external view returns (bool);
/// @notice True if `account` is on the sanctions/jurisdiction blocklist.
function isJurisdictionBlocked(address account) external view returns (bool);
/// @notice True only when timelocked governance approved `account` as a borrower-payout
/// destination and the account is not currently jurisdiction-blocked.
function isFundingRecipientAllowed(address account) external view returns (bool);
/// @notice True for a governance-designated internal protocol module.
function isProtocolExempt(address module) external view returns (bool);
/// @notice Transfer gate consulted by protocol tokens on every transfer. Transfers are
/// permissionless except for sanctioned (blocked) parties; burns are always
/// permitted; protocol modules are never treated as blocked.
/// @param token Retained for interface stability; no longer affects the result.
/// @param from Sender (zero on mint).
/// @param to Recipient (zero on burn).
/// @return True if the transfer may proceed.
function canTransfer(address token, address from, address to) external view returns (bool);
}
src/interfaces/IContinuousAccrual.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title IContinuousAccrual
/// @notice Reserve-owned accounting and exact delivery of previously accrued interest.
/// @dev Separate from the legacy reserve interface so activation is explicit. Amounts are
/// normalized to 18 decimals. Delivery changes physical balances, never economic ownership.
interface IContinuousAccrual {
/// @notice Modules bound to one independently backed chain instance.
/// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
struct Modules {
address token;
address controller;
address vault;
address waterfall;
address bridge;
address registry;
address defaultManager;
}
/// @notice Constant-time accounting, capped at the first unprocessed schedule boundary.
/// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
struct Snapshot {
uint256 gross;
uint256 unposted;
uint256 unissued;
uint256 seniorUnissued;
uint256 feeUnissued;
address feeRecipient;
uint64 accruedThrough;
bool enabled;
bool fresh;
}
/// @notice Vault-computed prices and permission for a neutral physical delivery.
/// @dev entryAssets includes any unvested assets; assets is the ordinary share-price base.
/// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
struct PricingState {
uint256 assets;
uint256 entryAssets;
uint256 redemptionAssets;
uint256 performanceAssets;
uint256 feeAdjustedShares;
bool materializationAllowed;
}
/// @notice One immutable, same-transaction permit and coherent public price snapshot.
/// @dev Unselected amounts are zero. A zero/default inactive record grants no authority.
/// @dev LAYOUT-FROZEN: embedded or array storage; changing its width shifts later live fields.
struct Delivery {
uint256 nonce;
uint256 senior;
uint256 fee;
uint256 effectiveSupply;
uint256 backing;
uint256 recognizedBacking;
PricingState pricing;
address controller;
address vault;
address feeRecipient;
uint64 accruedThrough;
uint8 legs;
bool active;
}
/// @notice Reads the configured module identities, including before activation.
function accrualModules() external view returns (Modules memory);
/// @notice Reads recognized income and its outstanding physical posting/issuance.
function accrualSnapshot() external view returns (Snapshot memory);
/// @notice Reads the current delivery permit, or an inactive default record.
function accrualDelivery() external view returns (Delivery memory);
/// @notice Refuses a price-sensitive write at an unresolved accrual boundary or operation.
function requireAccrualFresh() external view;
/// @notice Delivers selected existing claims: senior=1, fee=2, both=3.
/// @dev No amount, destination, timestamp or fee rate is supplied by the caller.
function materializeAccrued(uint8 legs) external returns (uint256 senior, uint256 fee);
}
/// @notice Token continuation accepting only the bound reserve's current exact permit.
interface IAccrualToken {
/// @notice The immutable-once-configured accounting reserve, or zero before binding.
function accrualReserve() external view returns (address);
/// @notice Mints the selected legs of one unused, active delivery permit.
function mintAccrued(uint256 nonce) external;
}
/// @notice Controller continuation, callable only by its configured reserve.
interface IAccrualController {
/// @notice Relays one exact reserve-owned delivery permit to the token.
function mintAccrued(uint256 nonce) external;
}
/// @notice Vault views needed to admit a neutral delivery without a guarded write callback.
interface IAccrualVault {
/// @notice The immutable-once-configured accounting reserve, or zero before binding.
function accrualReserve() external view returns (address);
/// @notice Supplies a coherent price snapshot and current delivery admission state.
function accrualPricingState() external view returns (IContinuousAccrual.PricingState memory);
}
/// @title IReliefPricingCache
/// @notice Optional exact-discount preparation; it grants no financial authority.
interface IReliefPricingCache {
/// @notice Derives reusable discounts from current protocol state, without caller-supplied values.
function prepareReliefPricing() external;
}
src/interfaces/IMintRedeemController.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @notice The one-bit pause surface of a wired module, declared here because `previewRedeem` must
/// read the reserve's pause and `IReserveManager` does not declare it.
/// @dev CANTINA 3.1.3 LIMB (a), CLOSED BY CONSTRUCTION ON THIS INSTANCE. On Ethereum the quote read
/// the controller pause and the token pause but not the reserve's, so it could publish a full
/// price for a redemption whose every release is `whenNotPaused`. The disposition there was
/// "an integrator should read `ReserveManager.paused()` alongside the quote", because closing
/// it was an upgrade. The mechanical reason the sibling fix missed the third surface is that
/// `ReserveManager` gets `paused()` from `PausableUpgradeable` and never declares it on its own
/// interface, so nothing in the type system pointed at it. This declaration is that pointer.
interface IPausableModule {
/// @notice True while the module refuses its `whenNotPaused` entry points.
function paused() external view returns (bool);
}
/// @title IMintRedeemController
/// @notice KYC-gated issuance and redemption of USDfr against canonical USDC, and the enforcement
/// point of the protocol's solvency rule. MINT is at par and is CLOSED while the protocol
/// is under-backed. REDEMPTION is at par while the protocol is whole; while it is short it
/// settles at the JUNIOR-DRAWN price, which is at least the coverage ratio and MAY BE PAR,
/// and which the caller must elect via `redeem(uint256,uint256)`.
/// AUDIT FIX (SWEEP-2 S2-I1) — THIS FILE-LEVEL LINE SAID "at the coverage ratio while it is
/// short", the THIRD round in which a false settlement claim sat on the one line an
/// explorer or ABI doc renders first. SWEEP-1 MRC-F2 corrected the two `redeem` overloads
/// and the contract-level block and left this headline. Falsified by the shipped
/// `ADR0034Y_AtomicJuniorExitDraw::test_Y_theExitSettlesAtParWhileCuratorCapitalStandsIntact`
/// and by SWEEP-2 S2-F3, in which a sub-par book settled at PAR because ADR-0034 Y-bis drew
/// junior capital forward to fund it.
/// @dev THE SOLVENCY RULE IS NOT ADR-0012's ABSOLUTE PREDICATE ANY MORE, AND THIS HEADLINE USED TO
/// SAY IT WAS (corrected in audit round R18). Until R18 this contract-level notice line read "KYC-gated 1:1
/// mint/redeem … `USDfr.totalSupply() <= backingValue()` after every supply-affecting op".
/// Both halves were false of the shipped code, and an auditor handed ADR-0012 plus this
/// interface as the specification would reasonably have reported "the contract does not
/// enforce its stated invariant" as a High. What the contract actually enforces:
/// - Redemption is NOT 1:1. R16-M3 made the exit price `backing / supply` while short, and
/// R17 gave the one-argument form a PAR FLOOR, so it reverts rather than settling short.
/// - The absolute predicate was REPLACED by the NON-WORSENING rule: an operation may not
/// increase `deficit = max(0, totalSupply - backingValue)`. While the protocol is whole
/// that reduces exactly to ADR-0012 and still reverts with
/// `Controller_BackingInvariantViolated`; while it is short it permits the operations that
/// repair holders' position and refuses the ones that dilute it. See
/// `MintRedeemController`'s contract-level NatSpec, which sets out the whole model.
/// - It is not asserted "after every supply-affecting op": `burnLoss` carries NO solvency
/// assertion, deliberately (finding M6 — the assertion it used to carry was unfalsifiable).
/// The comment was not independently wrong: it correctly quoted `ADR/0012-backing-invariant.md`
/// (Status: Accepted), which still states the superseded absolute rule verbatim as "a hard
/// on-chain check on every supply-affecting operation". THAT ADR MUST BE AMENDED OR SUPERSEDED
/// so the code and the decision record agree; it is OUTSTANDING and is Forest Road's to take
/// (CLAUDE.md §0.7).
interface IMintRedeemController {
// ── Events ───────────────────────────────────────────────────────────
event Minted(address indexed user, uint256 usdcIn, uint256 usdfrOut);
event Redeemed(address indexed user, uint256 usdfrIn, uint256 usdcOut);
/// @notice Emitted when USDfr is minted against attested yield receipts (waterfall path).
event YieldMinted(address indexed to, uint256 amount);
/// @notice Emitted when USDfr is burned to realize a loss (cascade layer 3).
event LossBurned(address indexed from, uint256 amount);
/// @notice AUDIT FIX (R16-M3). Emitted IN ADDITION to `Redeemed` when a redemption settled
/// below par because the protocol was under-backed. Carries the supply and backing
/// the quote was struck against, so the coverage ratio applied to any exit is
/// reconstructable purely from events (CLAUDE.md §3.1).
/// @param user The redeemer.
/// @param usdfrBurned USDfr burned (whole-USDC-unit aligned).
/// @param usdcOut Native USDC units actually paid out.
/// @param supply `totalUSDfr()` before the redemption.
/// @param backing `backingValue()` before the redemption.
event SubParRedemption(address indexed user, uint256 usdfrBurned, uint256 usdcOut, uint256 supply, uint256 backing);
/// @notice AUDIT FIX (R17). Emitted alongside `SubParRedemption`. Records the value
/// PERMANENTLY crystallised out of the senior layer by an exit priced against a
/// REVERSIBLE impairment mark, and the running total. `mintableHeadroom()` nets the
/// running total out, so value recovered when the mark is released stays in the pool
/// as coverage instead of being minted to the `sUSDfr` vault as yield.
/// @param user The redeemer who bore it.
/// @param amount `usdfrBurned - usdcOut * 1e12` for this exit, in 18-decimal USD.
/// @param cumulative `seniorSubParShortfall()` after this exit.
event SeniorShortfallCrystallised(address indexed user, uint256 amount, uint256 cumulative);
/// @notice AUDIT FIX (R16-M1). Governance authorized or revoked a `mintYield` destination.
event YieldSinkUpdated(address indexed account, bool authorized);
/// @notice AUDIT FIX (R16-M1/M2). Governance authorized or revoked a `burnLoss` source.
event LossSourceUpdated(address indexed account, bool authorized);
// ── Errors ───────────────────────────────────────────────────────────
error Controller_NotKYCAllowed(address account);
error Controller_BackingInvariantViolated(uint256 supply, uint256 backing);
error Controller_ZeroAmount();
error Controller_AmountTooSmall(uint256 usdfrAmount);
/// @notice An unratified arm refused a direct redemption.
/// @param armId Active custody arm.
/// @param usdcOut Proposed settlement in native USDC units.
/// @param usdfrIn USDfr claims proposed for redemption.
error Controller_ReserveLossArmFreeze(uint256 armId, uint256 usdcOut, uint256 usdfrIn);
/// @notice The redemption would have burned more USDfr than the post-draw supply.
/// @dev CANTINA 3.1.1, RE-DERIVED AT SCALE 1 AND CLOSED RATHER THAN ACKNOWLEDGED. On Ethereum
/// the whole-unit grid returned `M mod 1e12` wei of headroom at the top of the range, so
/// `usdfrIn + drawn` overflowed only for inputs within 1e12 of `type(uint256).max` - a
/// panic window of width at most 2**40, which is why "acknowledged" was a defensible
/// judgement. At scale 1 the grid is the identity, `usdfrIn == usdfrAmount` exactly, and
/// the window widens to the whole top `drawn` of the range. That is not the same judgement
/// about the same object. Bounding the SUM rather than the addend makes the overflow
/// UNREPRESENTABLE rather than merely unlikely, refuses only inputs no holder can hold, and
/// makes `previewRedeem` answer a controller error instead of `Panic(0x11)`.
/// @param usdfrIn The amount the exit would burn.
/// @param bound `supply - drawn`, which `supply - drawn <= supply` makes underflow-free because
/// `drawn` was burned out of `supply`.
error Controller_RedeemExceedsSupply(uint256 usdfrIn, uint256 bound);
/// @notice AUDIT FIX (R4-01): the user par paths are closed while the reserve holds less USDC
/// than its idle ledger claims. Recognition of the gap is permissionless and immediate;
/// restoring custody, or the authenticated custody-loss cascade writing the ledger down
/// to the live balance, reopens mint and redeem with no governance action.
/// @param shortfallValue The observable custody gap in 18-decimal USD.
/// @param recognizedBacking Backing net of that gap — the honest basis.
error Controller_ReserveCustodyShortfall(uint256 shortfallValue, uint256 recognizedBacking);
/// @notice AUDIT FIX (R16-M3/M4/M5). The operation would have WIDENED an already-standing
/// backing deficit. Distinct from `Controller_BackingInvariantViolated`, which is
/// raised when a whole protocol would be pushed below par: an integrator seeing that
/// error inside a knowingly sub-par protocol would reasonably read it as the standing
/// condition rather than as a refusal of this specific call.
/// @param deficitBefore `max(0, totalUSDfr() - backingValue())` before the operation.
/// @param deficitAfter The same quantity after it, which must not exceed `deficitBefore`.
error Controller_DeficitWorsened(uint256 deficitBefore, uint256 deficitAfter);
/// @notice A paired-yield baseline is already open, so a second cannot be started.
error Controller_PairedYieldAlreadyOpen(address caller);
/// @notice A split mint must consume this caller's existing paired backing baseline.
error Controller_PairedYieldRequired();
/// @notice A paired operation cannot complete against a changed retention obligation.
error Controller_PairedRetentionChanged(uint256 beforeRequirement, uint256 afterRequirement);
/// @notice The protocol fee cannot exceed the total amount being issued.
error Controller_InvalidYieldSplit(uint256 total, uint256 fee);
/// @notice A paired-yield baseline was recorded before its caller moved backing.
event PairedYieldOpened(address indexed caller, uint256 supplyBefore, uint256 backingBefore);
/// @notice A stranded paired-yield baseline was cleared by governance.
event PairedYieldCleared(address indexed caller);
/// @notice Records the supply/backing baseline for a yield mint whose backing leg moves first.
function beginPairedYield() external;
/// @notice Governance escape for a paired-yield baseline stranded by a reverted operation.
function clearStalePairedYield() external;
/// @notice AUDIT FIX (R16-M3). Par issuance is closed while the protocol is under-backed for
/// ANY reason — a G3 conservative mark or a residual cascade deficit as well as the
/// R4-01 custody gap. `redeem` deliberately stays OPEN in this state and re-prices to
/// the coverage ratio; see `previewRedeem`.
/// @param supply `totalUSDfr()` at the time of refusal.
/// @param backing `backingValue()` at the time of refusal.
error Controller_MintClosedWhileUnderBacked(uint256 supply, uint256 backing);
/// @notice AUDIT FIX (R16-L2). The USDC the user was charged did not arrive in the reserve's
/// custody, or the reserve credited a value that does not match it. Measured from the
/// reserve's own token balance rather than from anything the reserve reports about
/// itself, so `mint` no longer derives both sides of its safety check from one module.
/// @param requested Native USDC units pulled from the user.
/// @param delivered The reserve's measured USDC balance increase.
/// @param credited The 18-decimal value `depositUSDC` reported.
error Controller_DepositNotCustodied(uint256 requested, uint256 delivered, uint256 credited);
/// @notice AUDIT FIX (R16-M1). `to` is not a governance-authorized yield destination.
error Controller_NotYieldSink(address to);
/// @notice AUDIT FIX (R16-M1/M2). `from` is not a governance-authorized loss source. Without
/// this, `burnLoss` and `mintYield` composed into arbitrary confiscation, and
/// `USDfr.burn`'s allowance-free burn made any holder seizable one-sidedly.
error Controller_NotLossSource(address from);
/// @notice AUDIT FIX (R17). A loss source must be a CONTRACT. `burnLoss` burns with no
/// allowance, carries no backing assertion and is deliberately not pausable, so
/// listing an EOA would restore finding M2 — a forced, non-pro-rata seizure of one
/// named holder — in a single routine-looking timelock transaction. Mirrors
/// `ReserveManager.setLossAbsorber`/`setLossController`. Deliberately NOT applied to
/// `setYieldSink`, whose fee-recipient treasury may legitimately be an EOA.
error Controller_LossSourceNotContract(address account);
/// @notice AUDIT FIX (R17). The settled price was below the floor the caller named. The
/// one-argument `redeem` supplies the PAR floor, so it reverts with this rather than
/// silently haircutting a holder against a mark that may later be released.
/// @param usdcOut What the redemption would have paid.
/// @param minUsdcOut The floor the caller required.
error Controller_SlippageExceeded(uint256 usdcOut, uint256 minUsdcOut);
/// @notice AUDIT FIX (R17). Backing has fallen to zero, so there is nothing to pay out at any
/// size. Previously this answered `Controller_AmountTooSmall`, which told the holder
/// their amount was the problem when the truth was that the protocol was worth nothing.
/// @param supply `totalUSDfr()` at the time of refusal.
error Controller_NoRedeemableBacking(uint256 supply);
/// @notice AUDIT FIX (R17). The USDC the redemption was priced at did not reach the redeemer.
/// The outflow twin of `Controller_DepositNotCustodied`: R16-L2 installed an
/// independent measurement on the inflow leg only, leaving `redeem` to take the
/// reserve's own word for a release on the leg where the holder's USDfr is already
/// burned and the loss is irreversible.
/// @param expected The quoted payout in native USDC units.
/// @param settled The redeemer's measured USDC balance increase.
/// @param usdfrBurned The USDfr burned to pay for it.
error Controller_RedemptionNotSettled(uint256 expected, uint256 settled, uint256 usdfrBurned);
/// @notice AUDIT FIX (R17). USDC was left sitting on the controller after a mint. The
/// controller is value-neutral at rest; a reserve that funded the deposit from
/// somewhere other than the controller's allowance satisfies the delivery equality
/// while leaving the user's cash here with a live approval against it.
/// @dev Measured as a DELTA across the call, never as an absolute balance: anyone can send
/// USDC to the controller, so `balanceOf(this) != 0` would be a one-wei permanent
/// griefing lock on `mint`.
/// @param balanceBefore The controller's USDC balance before the deposit leg.
/// @param balanceAfter Its balance after it. Any inequality is refused.
error Controller_CashStrandedOnController(uint256 balanceBefore, uint256 balanceAfter);
/// @notice AUDIT FIX (R17). The operation would have widened the deficit measured on the
/// RECOGNITION-AWARE basis — backing net of the custody shortfall the reserve can
/// observe right now. Raised only by `mintYield`, the one supply-EXPANDING path with
/// no custody precondition; `mint` and `redeem` are refused earlier by
/// `Controller_ReserveCustodyShortfall`, and `burnLoss` is deliberately ungated.
/// @param deficitBefore `max(0, totalUSDfr() - recognizedBackingValue())` before the call.
/// @param deficitAfter The same quantity after it.
error Controller_RecognizedDeficitWorsened(uint256 deficitBefore, uint256 deficitAfter);
/// @notice AUDIT FIX (R17). A yield mint would have consumed value retained against
/// `seniorSubParShortfall()` — the haircut crystallised out of holders who exited
/// against a REVERSIBLE impairment mark. `mintableHeadroom()` advertises the retention;
/// this error enforces it.
/// @dev CORRECTED (SWEEP-1 MRC-F3, 2026-08-08). This sentence used to end "...because
/// `WaterfallEngine.fund`'s origination-fee mint is not sized off that headroom and would
/// otherwise spend it." THAT JUSTIFICATION EXPIRED AT R18. `WaterfallEngine.fund` now
/// reads `uint256 headroom = $.controller.mintableHeadroom();` and clamps
/// `mintable = fee <= headroom ? fee : headroom` (WaterfallEngine.sol:195-197);
/// `MintRedeemController` says so in two places, and
/// `test_R18_A1_originationSurvivesACrystallisedHaircut` passes over the clamped path.
/// This is the same class of defect the merge author fixed on
/// `CollateralRegistry.conservativeSeniorMark`: a stale justification on a value path is
/// a defect, because the next engineer prunes the guard once they discover the reason
/// given for it is untrue.
///
/// THE ERROR IS STILL LOAD-BEARING, ON A DIFFERENT GROUND — DO NOT DELETE IT. It is the
/// LAST line of defence rather than the only one. `CREDIT_ROLE` gates `mintYield`, and
/// `Deploy.s.sol` grants that role to `WaterfallEngine` alone TODAY; a second grantee, or
/// any future unclamped call site, would spend the junior retention silently. The clamp is
/// a caller-side property; this is the callee-side one.
/// @param threshold THE BOUND THAT WAS ACTUALLY ENFORCED, which differs by branch and is why
/// this parameter is not named `retention`. On an ordinary yield mint it is
/// `seniorSubParShortfall()`, the junior retention the surplus must not fall below. On a
/// PAIRED mint opened by `beginPairedYield` it is the surplus recorded BEFORE the caller
/// moved any backing, because a paired move raises backing and supply by the identical
/// amount and the property enforced there is exact neutrality rather than a floor.
/// Reporting the retention on the paired branch made the error describe a rule that
/// branch does not apply; corrected 2026-09-10.
/// @param surplus `max(0, recognizedBackingValue() - totalUSDfr())` after the mint.
error Controller_SeniorRetentionBreached(uint256 threshold, uint256 surplus);
/// @notice AUDIT FIX (R18). The reserve took the USDC and reported the right credit but did not
/// BOOK it as backing. The recognition twin of `Controller_DepositNotCustodied`: R16-L2
/// measured custody and R17 measured the reported credit, while recognition was left to
/// the NON-WORSENING deficit rule — which a standing surplus silently pays for, up to
/// its own size. Measured as a DELTA on `backingValue()` across the deposit leg, so no
/// surplus can absorb it, and as an EQUALITY, so an over-booking reserve is refused too.
/// @param credited The 18-decimal value `depositUSDC` reported.
/// @param recognized The measured increase in `backingValue()` across the same call.
error Controller_DepositNotRecognized(uint256 credited, uint256 recognized);
/// @notice AUDIT FIX (R18). A loss source must not be an EIP-7702 DELEGATED EOA. Since Pectra
/// an ordinary key-controlled wallet that signed a delegation carries a 23-byte
/// `0xef0100`-prefixed code field, so `EXTCODESIZE` returns 23 and
/// `Controller_LossSourceNotContract`'s check admitted it — leaving finding M2 (a
/// forced, allowance-free, non-pro-rata seizure of one named holder, unstoppable by the
/// guardian) one routine-looking timelock transaction away for exactly the class of
/// wallet the guard claimed to exclude.
error Controller_LossSourceIsDelegatedEOA(address account);
/// @notice AUDIT FIX (R18). A composite view was read while this contract's reentrancy guard
/// was entered — i.e. from inside a supply change that has not finished settling — and
/// would have answered a number known to be false.
/// @dev `_redeem` burns before it releases, and `DefaultManager.realizeLoss` burns before it
/// writes backing down; `USDfr._update` fires the participation-points hook inside every
/// one of those burns. From there `mintableHeadroom()` read the entire realised loss of a
/// cascade as distributable yield capacity, `backingInvariantHolds()` read TRUE on a short
/// book and `previewRedeem` quoted PAR on it. Reverting is the honest answer and is
/// fail-closed for an integrator; returning the number is the R4-01 self-contradiction one
/// frame deeper. The raw delegating views (`backingValue`, `recognizedBackingValue`,
/// `totalUSDfr`) are NOT gated: each is true whenever it is read. Only the composites are.
error Controller_ViewUnavailableMidTransition();
/// @notice `redeem(uint256,uint256,uint256)` was included after the caller's deadline
/// (ADR-0034 W).
error Controller_DeadlinePassed(uint256 deadline, uint256 nowTimestamp);
/// @notice The junior-draw source named by `ReserveManager.lossAbsorber()` is not on the
/// governance-maintained `setLossSource` list (ADR-0034 Y-bis). Fail-closed: the exit
/// refuses rather than burning a third party's USDfr on an unvouched-for pointer.
error Controller_ExitDrawSourceNotAuthorised(address source);
/// @notice The junior-draw source reported one number and moved another, or delivered more
/// than was asked of it (ADR-0034 Y-bis). Measured, not trusted.
error Controller_ExitDrawNotDelivered(uint256 requested, uint256 reported, uint256 measured);
/// @notice Junior capital was drawn forward, in cascade order, to fund this exit's price
/// (ADR-0034 Y-bis). `drawn` USDfr was burned out of the junior layers.
event SeniorExitJuniorDrawn(address indexed redeemer, uint256 required, uint256 drawn);
// ── User paths (KYC-gated) ───────────────────────────────────────────
/// @notice Deposits USDC (6 decimals) and mints USDfr 1:1 in 18-decimal USD units.
function mint(uint256 usdcAmount) external returns (uint256 usdfrOut);
/// @notice Burns USDfr and releases the reserve's cash equivalent AT PAR. While the protocol
/// is short this form settles at par out of JUNIOR capital drawn forward in the same
/// transaction (ADR-0034 Y-bis), and reverts `Controller_SlippageExceeded` only once
/// that draw cannot reach par. It never haircuts the caller. Use
/// `redeem(uint256,uint256)` to elect a sub-par exit.
/// @dev AUDIT FIX (R18) CORRECTED THE NOTICE LINE ABOVE, which every block explorer, ABI
/// doc and integrator reads first. It said this form is "priced at the coverage ratio: par
/// while the protocol is whole, `backing / supply` while it is short". After R17's par
/// floor that is false of THIS form. The coverage-ratio behaviour described below is
/// R16-M3's and is true of the two-argument form.
/// @dev CORRECTED AGAIN (SWEEP-1 MRC-F2, 2026-08-08) — SAME LINE, ONE ROUND LATER. R18's
/// replacement said this form "REVERTS" while short, full stop. That stopped being true
/// at ADR-0034 Y-bis, which draws curator first-loss and the sGROVE backstop forward in
/// the same transaction to fund the cascade-ordered price. MEASURED: with a gross quote of
/// 185,928.705440 USDC this form settled 200,000.000000 — AT PAR, out of junior capital.
/// It reverts only when the draw cannot reach par. Two successive rounds put a false
/// settlement claim on the one line integrators read first; check it against
/// `MintRedeemController._quoteRedeem` and `_drawJuniorForExit` before editing it again.
/// @dev AUDIT FIX (R17): THIS FORM SUPPLIES THE PAR FLOOR. It settles at par or reverts with
/// `Controller_SlippageExceeded`. R16 made the price a live function of state and left
/// this one-argument signature accepting whatever the ratio was at inclusion, while
/// several NON-timelocked paths move backing down in the same block. Taking a haircut is
/// now an explicit election: quote with `previewRedeem`, then call the two-argument form
/// with the floor you will accept.
function redeem(uint256 usdfrAmount) external returns (uint256 usdcOut);
/// @notice Burns USDfr and releases the reserve's cash equivalent, refusing to settle below
/// `minUsdcOut`. This is the form that accepts a SUB-PAR exit — an explicit, informed
/// election by the holder (R16-M3, R17).
/// @dev CORRECTED (SWEEP-1 MRC-F2, 2026-08-08). This line said the form "pays the COVERAGE
/// RATIO". It pays the JUNIOR-DRAWN price, which is >= the coverage ratio and may be par:
/// ADR-0034 Y-bis draws curator first-loss and the sGROVE backstop forward in the same
/// transaction, and the gross `backing / supply` mark is only the floor the price degrades
/// to once junior capital is exhausted. Quote with `previewRedeem`, which shares the
/// drawn arithmetic.
/// @dev AUDIT FIX (R17). `previewRedeem` is advisory ACROSS TRANSACTIONS — it shares
/// `redeem`'s arithmetic, not its state — so this parameter is the only thing that binds
/// the settlement price. Pass the value `previewRedeem` returned (or lower, to tolerate
/// movement).
/// @dev THE DEADLINE IS NOW SHIPPED, ON A NEW SIGNATURE (ADR-0034 W). R17 wrote here that
/// "there is no deadline parameter: there is no AMM-style path here, and the floor alone
/// is sufficient to make the exit refusable", which argued an ACCEPTED requirement away.
/// `redeem(uint256,uint256,uint256)` carries it. THIS form is deliberately left
/// deadline-free rather than being given a new expiry semantic under an unchanged
/// signature — see that overload's NatSpec. Prefer the three-argument form.
/// @param usdfrAmount USDfr offered; the burn is snapped down to the whole-USDC-unit grid.
/// @param minUsdcOut The lowest native-USDC payout the caller will accept. Zero accepts ANY
/// price, including a deep haircut — pass zero only deliberately.
function redeem(uint256 usdfrAmount, uint256 minUsdcOut) external returns (uint256 usdcOut);
/// @notice Burns USDfr and releases the reserve's cash equivalent, refusing to settle below
/// `minUsdcOut` or after `deadline`. THE CANONICAL EXIT (ADR-0034 W).
/// @dev A minimum-out bounds the PRICE; it does not bound WHEN the exit executes. Every path
/// that moves the coverage ratio down is un-timelocked and publicly visible before it
/// lands, so a transaction left in the mempool is a free option for whoever chooses
/// inclusion. See the implementation NatSpec.
/// @param usdfrAmount USDfr offered; the burn is snapped down to the whole-USDC-unit grid.
/// @param minUsdcOut The lowest native-USDC payout the caller will accept.
/// @param deadline Latest `block.timestamp` at which this exit may settle.
function redeem(uint256 usdfrAmount, uint256 minUsdcOut, uint256 deadline) external returns (uint256 usdcOut);
// ── Protocol paths (credit layer; wired in Phases E/G) ───────────────
/// @notice Mints USDfr to `to` against newly received, attested backing (loan
/// interest / reserve yield). `CREDIT_ROLE`.
/// @dev AUDIT FIX (R16-M1): `to` must be a governance-authorized yield sink. Refuses while
/// the protocol is under-backed (incoming cash repairs the hole before it is paid out
/// as yield) and while the controller is paused (a pause must never permit supply
/// expansion). Callers should size the mint with `mintableHeadroom()`.
/// @dev AUDIT FIX (R17/R18): it ALSO refuses while the surplus is below
/// `seniorSubParShortfall()` (`Controller_SeniorRetentionBreached`) — an ABSOLUTE level
/// check that bites in states the protocol publishes as fully backed. EVERY CALLER MUST
/// SIZE ITSELF OFF `mintableHeadroom()`: it is the one view that nets the retention, both
/// pauses and the recognition basis. `WaterfallEngine` now does so on BOTH of its mints
/// (interest since R16-M5, the origination fee since R18); a caller that does not will
/// revert rather than withhold.
function mintYield(address to, uint256 amount) external;
/// @notice Issues one paired increase to two authorized sinks, checking the complete total.
/// @param senior Destination of total minus fee; unused when that amount is zero.
/// @param total Total new supply, justified by the backing increase since beginPairedYield.
/// @param feeRecipient Destination of fee; unused when fee is zero.
/// @param fee Part of total allocated before the senior leg, in normalized USDfr units.
function mintYieldSplit(address senior, uint256 total, address feeRecipient, uint256 fee) external;
/// @notice Burns USDfr from `from` to realize a loss through the cascade.
/// `LOSS_BURNER_ROLE` — deliberately NOT `CREDIT_ROLE`.
/// @dev AUDIT FIX (R16-M1/M2): `from` must be a governance-authorized loss source, and the
/// role is split from `CREDIT_ROLE` so `WaterfallEngine`, which never burns, no longer
/// holds the power to. Never pausable: loss absorption must stay available.
function burnLoss(address from, uint256 amount) external;
// ── Governance: credit-layer endpoints (AUDIT FIX R16-M1) ────────────
/// @notice Authorizes (or revokes) an address as a destination for `mintYield`.
function setYieldSink(address account, bool authorized) external;
/// @notice Authorizes (or revokes) an address as a source for `burnLoss`.
function setLossSource(address account, bool authorized) external;
// ── Views ────────────────────────────────────────────────────────────
/// @notice Current backing value on the RECORDED-LEDGER basis
/// (delegates to `ReserveManager.totalBackingValue()`).
/// @dev AUDIT FIX (R4-01): this is the basis the C-01 custody-loss arithmetic reconciles
/// against within a single transaction and is deliberately NOT recognition-aware. For any
/// solvency or exit-pricing question use `recognizedBackingValue()`.
function backingValue() external view returns (uint256);
/// @notice AUDIT FIX (R4-01). Backing net of the custody shortfall the reserve can observe
/// right now (delegates to `ReserveManager.recognizedBackingValue()`).
function recognizedBackingValue() external view returns (uint256);
/// @notice Current USDfr total supply.
function totalUSDfr() external view returns (uint256);
/// @notice True if supply is covered on the RECORDED ledger.
/// @dev Compatibility diagnostic only. DELIBERATELY BLIND TO THE CUSTODY SHORTFALL and no
/// longer consumed by `WaterfallEngine.distribute`: that path enforces exact receipt and
/// a non-worsening recognised deficit. Do not use this absolute view as an admission
/// gate, user-path condition, exit price, or solvency display.
function creditServicingBackingHolds() external view returns (bool);
/// @notice True if the backing invariant currently holds. Public so anyone can check.
/// @dev AUDIT FIX (R4-01): measured against `recognizedBackingValue()`, so it can no longer
/// report true in the same block in which `observeIdleUSDC()` publishes a shortfall.
/// @dev AUDIT FIX (R18): reverts with `Controller_ViewUnavailableMidTransition` if called from
/// inside an unsettled supply change — mid-burn it read TRUE on a 20%-short book.
function backingInvariantHolds() external view returns (bool);
/// @notice AUDIT FIX (R16-M4/M5). `max(0, totalUSDfr() - backingValue())` on the RECORDED
/// basis — the quantity every supply-affecting path refuses to increase.
/// @dev AUDIT FIX (R18): reverts with `Controller_ViewUnavailableMidTransition` if called from
/// inside an unsettled supply change; it composes a supply reading with a backing reading.
function backingDeficit() external view returns (uint256);
/// @notice AUDIT FIX (R16-M4). The same quantity on the RECOGNITION-AWARE basis (net of any
/// observable custody shortfall).
/// @dev This is what `WaterfallEngine.distribute` gates on, comparing it before and after the
/// call. Non-worsening rather than absolute, so a repayment that REPAIRS backing is not
/// refused merely because the protocol was already short — which is what previously
/// turned a single conservative mark into a total halt of repayment processing.
/// @dev AUDIT FIX (R18): reverts with `Controller_ViewUnavailableMidTransition` if called from
/// inside an unsettled supply change, as `backingDeficit()` does.
function recognizedDeficit() external view returns (uint256);
/// @notice AUDIT FIX (R16-M5, corrected by R17, R18 and SWEEP-2 S2-F4). How much NEW supply may
/// be minted without widening the deficit or paying away value the protocol owes:
/// `(paused() || USDfr.paused()) ? 0 : max(0, recognizedBackingValue() - totalUSDfr() -
/// seniorSubParShortfall() - ReserveManager.exitPrepaidAbsorption())`.
/// @dev AUDIT FIX (SWEEP-2 S2-F4) — THE FOURTH TERM WAS MISSING FROM THIS PUBLISHED FORMULA, AND
/// THE STRING `exitPrepaid` APPEARED NOWHERE IN THIS FILE. ADR-0034 Y-bis added
/// `ReserveManager.exitPrepaidAbsorption()` to the implementation and not to the
/// specification. This is the one view that decides how much yield may be minted, and
/// `mintYield`'s note below warns that "a caller that does not size itself off
/// `mintableHeadroom()` will revert rather than withhold" — so a caller sizing off the
/// PUBLISHED formula got `Controller_SeniorRetentionBreached` /
/// `Controller_RecognizedDeficitWorsened` instead of a withholding. MEASURED: published
/// formula 9,900.99e18, code 0, undocumented term 9,900.99e18. The retention has NO
/// RESTITUTION PATH and is not necessarily released — see `mintableHeadroom`'s own
/// implementation note and the SWEEP-2 S2-F3 register entry.
/// @dev AUDIT FIX (R18): the pause term reads BOTH pauses. R17 read only the controller's, while
/// the same guardian key holds `GUARDIAN_ROLE` on `USDfr` and a token pause refuses every
/// mint — so one transaction still reverted every interest-bearing
/// `WaterfallEngine.distribute` in full. `WaterfallEngine.fund` now sizes its origination
/// fee off this view as well, so under either pause it withholds the fee instead of
/// reverting the origination.
/// @dev AUDIT FIX (R18): reverts with `Controller_ViewUnavailableMidTransition` if called from
/// inside an unsettled supply change — mid-cascade it read the entire realised loss as
/// distributable yield capacity.
/// @dev `WaterfallEngine._routeInterest` reads this and distributes only what fits,
/// WITHHOLDING the rest so the cash stays in the reserve and repairs backing. That is
/// the protocol-native cure for a residual deficit: loan interest closes the hole
/// automatically, with no governance action and no recapitalisation, and yield resumes
/// by itself once it is closed.
/// @dev AUDIT FIX (R17): the basis is RECOGNITION-AWARE. Measured on the recorded ledger the
/// cure was blind to the entire deficit class R4-01 exists to recognise — a custody hole
/// left headroom equal to the whole interest receipt, so the clamp withheld nothing, the
/// protocol fee was taken on the gross, and the hole never closed while every user was
/// frozen out of `mint` and `redeem`. It is also zero while the controller is PAUSED, so
/// the pause withholds yield instead of reverting every borrower repayment, and it nets
/// out `seniorSubParShortfall()`.
function mintableHeadroom() external view returns (uint256);
/// @notice AUDIT FIX (R17). Cumulative value crystallised out of the senior layer by sub-par
/// exits, in 18-decimal USD. Monotonically non-decreasing; no setter.
/// @dev Sub-par exits are priced against `recognizePrincipalImpairment` marks, which are
/// REVERSIBLE by design (`releasePrincipalImpairment`). The exiter's loss is not. Without
/// this, value recovered when a mark is released reappeared as `mintableHeadroom()` and
/// was minted to the `sUSDfr` vault — the senior's haircut becoming the yield layer's
/// income, ahead of the §1.3 cascade's first two layers. Netting it out of the headroom
/// keeps recovered value in the pool as coverage instead. Reconstructable from
/// `SeniorShortfallCrystallised` events.
/// @dev AUDIT FIX (R18) — WHAT IT COSTS, CORRECTED. `mintYield` enforces this as an ABSOLUTE
/// level check, so it withholds ORIGINATION FEES as well as interest, and it does so in
/// states the protocol publishes as fully backed and even OVER-backed. Under R17 that
/// REFUSED `WaterfallEngine.fund` outright and therefore blocked the only cure the
/// mechanism names (interest requires a facility; a facility requires `fund`) — finding M5
/// on the origination axis. `fund` now clamps its fee to `mintableHeadroom()` and withholds
/// instead. The retention is unchanged. Read `MintRedeemController.seniorSubParShortfall`
/// for the full statement, including the known over-charge on a REALISED (as opposed to
/// released) loss, which is outstanding.
function seniorSubParShortfall() external view returns (uint256);
/// @notice AUDIT FIX (R16-M3/L3). Quotes a redemption without executing it: the USDC that
/// would be paid and the USDfr that would actually be burned.
/// @dev Returns `(0, 0)` — BOTH components — in FOUR cases: the amount is below the settleable
/// floor; the protocol has no backing; the protocol is empty (`totalUSDfr() == 0`); or
/// REDEMPTION IS CLOSED because the reserve has an unreconciled custody shortfall
/// (`idleCustodyShortfall() != 0`, AUDIT FIX R18). In all four, nothing is payable at any
/// size, which is what `(0, 0)` has always meant here. A frontend can therefore state the
/// floor, or state that redemption is unavailable, without simulating a revert.
/// @dev AUDIT FIX (R18) added the fourth case. R17 changed WHICH number this published over a
/// custody hole; it did not change WHETHER one was published, so in the standing R4-01
/// state — where `backingInvariantHolds()` already publishes FALSE — this returned a full,
/// settleable-looking quote for a call that `_requireCustodiedReserve` then refuses with
/// `Controller_ReserveCustodyShortfall`. Passing that number back in as `minUsdcOut`, as
/// the sentence above directs, reverted.
/// @dev AUDIT FIX (R18): reverts with `Controller_ViewUnavailableMidTransition` if called from
/// inside an unsettled supply change (the participation-points hook fires mid-burn, where
/// this view quoted PAR on a short book).
/// @dev AUDIT FIX (R17), correcting R16's claim that "quote and settlement cannot diverge".
/// This view shares `redeem`'s ARITHMETIC; it does not share `redeem`'s preconditions and
/// it does not bind the price. Two consequences a caller must know:
/// - It is priced on `recognizedBackingValue()`, because unlike `redeem` it is not
/// behind `_requireCustodiedReserve`. On the recorded basis it published a par quote
/// in exactly the state where the recorded ledger is known to be false and the call it
/// quoted for would revert. Wherever `redeem` is reachable the two bases are equal, so
/// the quote is exact there.
/// - It is a snapshot of the current state, valid for that state only. Pass it back into
/// `redeem(usdfrAmount, minUsdcOut)`; that parameter, not this view, is what binds.
function previewRedeem(uint256 usdfrAmount) external view returns (uint256 usdcOut, uint256 usdfrIn);
/// @notice AUDIT FIX (R16-M1). True if `account` may receive `mintYield`.
function isYieldSink(address account) external view returns (bool);
/// @notice AUDIT FIX (R16-M1/M2). True if `account` may be burned from by `burnLoss`.
function isLossSource(address account) external view returns (bool);
/// @notice Wired module addresses, used to bind ReserveManager's independent loss check to
/// the controller that actually points back to that reserve.
function modules() external view returns (address usdfr, address compliance, address reserves);
}
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/ISeniorExitDrawSource.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title ISeniorExitDrawSource — the atomic junior draw behind a cascade-ordered exit price
/// @notice ADR-0034 Y-bis. The narrow surface `MintRedeemController._redeem` needs from the loss
/// cascade, kept separate from the full `IDefaultManager` so the controller takes a
/// dependency on ONE function rather than on the whole default-management surface.
/// @dev THE CONTRACT WITH THE CALLER, and every clause is load-bearing:
///
/// 1. ORDER. The implementation MUST consult curator first-loss BEFORE the sGROVE backstop,
/// and MUST offer the backstop only what layer 1 declined. The controller cannot check
/// this — it has no vocabulary for "layer" — so the ordering guarantee lives entirely in
/// the implementation's dataflow. `DefaultManager.drawForSeniorExit` is the reference.
///
/// 2. DELIVERY. Exactly `drawn` USDfr MUST be standing at the implementation's own address
/// when this returns, over and above what it held on entry. The CALLER burns it in place;
/// the implementation MUST NOT call back into `MintRedeemController.burnLoss`, which is
/// `nonReentrant` on a controller already inside `redeem`.
///
/// 3. NEVER MORE THAN ASKED. `drawn <= required`. The controller measures the delta itself
/// and refuses to settle if the report and the movement disagree, so an implementation
/// that lies can only cause a revert — never an overpayment out of junior capital.
///
/// 4. NEVER REVERT ON INSUFFICIENCY. `drawn < required` (including zero) is an ordinary
/// answer. Reverting would reintroduce the R16 exit deadlock ADR-0034 exists to remove.
interface ISeniorExitDrawSource {
/// @notice Draws junior capital forward, in cascade order, to fund a senior exit price.
/// @param required Junior capital the exit price needs, in 18-decimal USDfr units.
/// @return drawn USDfr actually provided by layers 1 and 2, standing at this contract.
function drawForSeniorExit(uint256 required) external returns (uint256 drawn);
}
src/interfaces/IUSDfr.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title IUSDfr
/// @notice The fully-backed synthetic dollar (brief Part 4). Mint/burn restricted to the
/// controller; optional compliance module consulted on transfers.
interface IUSDfr is IERC20 {
/// @notice Emitted when the compliance module address is updated.
event ComplianceModuleUpdated(address indexed module);
/// @notice Emitted when the participation-points hook changes.
event PointsModuleUpdated(address indexed module);
/// @notice Emitted when the (fail-open) points hook reverted on a transfer (P-04 telemetry).
event PointsHookFailed(address indexed from, address indexed to, uint256 value);
/// @notice Transfer blocked by the compliance module.
error USDfr_TransferNotAllowed(address from, address to);
/// @notice Mints `amount` to `to`. Only MINTER_ROLE (the MintRedeemController).
function mint(address to, uint256 amount) external;
/// @notice Burns `amount` from `from`. Only MINTER_ROLE (the controller).
function burn(address from, uint256 amount) external;
/// @notice The compliance registry consulted on transfers.
/// @dev AUDIT FIX (C4-USDFR-03): this used to read "zero = no restriction", which is FALSE
/// and dangerously so. Zero does disable the sanctions transfer gate, but the registry
/// is ALSO the only on-chain directory of protocol modules, and USDfr's emergency-pause
/// carve-out is keyed off that directory. With no registry a pause is TOTAL — the loss
/// cascade's burn leg included. Zero is a MORE restrictive setting exactly when
/// restriction is most damaging, not a less restrictive one.
function complianceModule() external view returns (address);
/// @notice Sets the compliance registry. Only DEFAULT_ADMIN_ROLE (timelocked governance).
/// Clearing it (zero) is refused while the token is paused — see
/// `USDfr.setComplianceModule` (C4-USDFR-03).
function setComplianceModule(address module) external;
/// @notice True while the token's own emergency pause is engaged.
/// @dev AUDIT FIX (R18) — ADDED SO THE CONTROLLER CAN SEE THIS PAUSE. `USDfr._update` refuses
/// every MINT while the token is paused (its protocol-leg carve-out requires
/// `from != address(0)`, which a mint can never satisfy), and the same guardian address
/// holds `GUARDIAN_ROLE` here and on `MintRedeemController`. R17 made
/// `MintRedeemController.mintableHeadroom()` read zero under a CONTROLLER pause so
/// `WaterfallEngine._routeInterest` would WITHHOLD instead of reverting an entire borrower
/// repayment — but it could not see this pause, so one un-timelocked `USDfr.pause()` still
/// reverted every interest-bearing `distribute` in full, principal leg included. The
/// headroom now reads both pauses, and that requires this to be on the interface rather
/// than reached through a local ad-hoc declaration.
function paused() external view returns (bool);
}
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.