Verified contractExactBUSL-1.1
RedemptionQueue
Address0x35e39a47df8afe08f953ffa0e81c8c82c925fe4a
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.30
- Same code
Only this contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 100 runs
- EVM version
- cancun
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,486,095
- Creation transaction
- 0xd6192d3b66…69ab196256
32 files
- src/RedemptionQueue.solmain48.92 KB
- lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol8.33 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol9.28 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol6.57 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol1.19 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol3.66 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol4.51 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol1.15 KB
- lib/openzeppelin-contracts/contracts/access/IAccessControl.sol3.34 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol193 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol637 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol182 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol12.18 KB
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol882 B
- lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol6.24 KB
- lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol473 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol10.08 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6 KB
- lib/openzeppelin-contracts/contracts/utils/Errors.sol896 B
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4.18 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol32.15 KB
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- src/interfaces/IRedemptionQueue.sol13.29 KB
- src/interfaces/IReserveManager.sol31.28 KB
- src/interfaces/IsUSDfr.sol14.06 KB
- src/libraries/Config.sol23.1 KB
- src/libraries/Roles.sol4.2 KB
src/RedemptionQueue.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 {IRedemptionQueue} from "./interfaces/IRedemptionQueue.sol";
import {IReserveManager} from "./interfaces/IReserveManager.sol";
import {IsUSDfr} from "./interfaces/IsUSDfr.sol";
import {Config} from "./libraries/Config.sol";
import {Roles} from "./libraries/Roles.sol";
/// @title RedemptionQueue — epoch FIFO exits for sUSDfr (ADR-0010, the QEV analog)
/// @notice Because deployed capital is illiquid (amortizing facilities), sUSDfr never
/// redeems instantly: exits queue here and settle at epoch close, strictly
/// FIFO, against a liquidity budget snapshotted per settlement — the
/// governance-set share of the treasury's STABLE liquidity only (the
/// reserve-instrument mark is a valuation, not cash). The vault admits this
/// contract as its sole withdraw/redeem caller (`sUSDfr.setRedemptionQueue`).
///
/// BUDGET SEMANTICS (AUDIT NOTE R2-M-01 — honest framing): the settlement budget is
/// a per-epoch THROUGHPUT CAP on how many sUSDfr shares convert to USDfr claims — it
/// is NOT an escrow or a reservation of stablecoins. Queue claimants are paid in
/// USDfr (fully backed) and later convert USDfr→stable via the controller, drawing
/// the SAME unreserved stable pool as direct USDfr redeemers; nothing here earmarks
/// stables for the queue. So a claimant's USDfr is safe (backed), but the *timing* of
/// its stable conversion competes with direct redemptions — the budget bounds
/// issuance of claims, it does not guarantee downstream stable liquidity. A hard
/// reservation is an economic-review item (deliberately not a rushed escrow here).
///
/// SETTLEMENT MODEL: `closeEpoch` is KEEPER-GATED (`SETTLEMENT_KEEPER_ROLE`,
/// superseding ADR-0018 §2 — see the role's NatSpec) and chunked (`maxRequests`
/// per call — no unbounded loops). The first call past the epoch end snapshots
/// the budget; fills proceed head-first, the head request may fill partially,
/// and settlement completes when the queue, the budget, or its dust runs out,
/// or when the head's fill would be worth zero USDfr at the conservative
/// redemption rate (C-1: such a fill is never taken — nothing is ever burned for
/// nothing) — then the next epoch opens. Requests joining mid-settlement queue
/// behind the current tail and are eligible within the same settlement if budget
/// remains (still strictly FIFO).
///
/// C-1 ZERO-VALUE HANDLING (strict FIFO, NO reordering): a head whose fill prices
/// to zero is NEVER burned. It has two causes, both stopping the settlement with the
/// head keeping its FIFO place:
/// (a) the BUDGET cannot buy a nonzero slice of a head that is itself worth
/// something → stop (`Queue_NoLiquidity`); the head settles later at a real price.
/// (b) the head's ENTIRE remaining position prices to zero — worth < 1 wei of USDfr
/// at the conservative exit NAV, i.e. the senior front is not redeemable →
/// settlement stops LOUDLY with `Queue_HeadNotRedeemable`. The heartbeat is not
/// consumed, nothing is burned, and `headValuation()` exposes the state to
/// monitoring. It clears when the mark is cured or realized.
/// A sub-wei "dust" head is NOT deferred/requeued. The `minRedemptionValue` entry
/// floor (default $1, REALIZED rate) bars CHEAP griefing — a $0-cost dust head that
/// blocks real positions. It does NOT by itself bound the CONSERVATIVE-rate value that
/// triggers (b): a large DECLARED (unrealized) impairment can price a legally-entered
/// head to 0 conservative while a materially larger position behind it stays
/// redeemable, so (b) is reachable there, not only under a realized near-total loss.
/// That residual is bounded and self-resolving — the blocked large redeemer would only
/// ever settle at a near-total-loss conservative price anyway, and the halt clears when
/// the mark cures or realizes — so strict FIFO with no reordering, no deferral, and no
/// unbounded array growth remains the right trade. The floor removes the cheap-griefing
/// surface; it is not claimed to make the wedge impossible.
///
/// ADR-0016 NOTE (points): queued shares sit at this contract's address, which
/// is not identity-bound in the PointsModule — participation accrual for the
/// requester STOPS at request time by construction (exit intent is the end of
/// participation), and the queue itself accrues nothing. Asserted in tests.
///
/// §1.3 INVARIANTS OWED HERE (encoded in RedemptionQueueInvariants):
/// distributed assets never exceed the settlement budget; FIFO never inverts
/// (a fill implies every earlier request is fully filled — no reordering); no
/// double-claim.
contract RedemptionQueue is
Initializable,
AccessControlUpgradeable,
PausableUpgradeable,
ReentrancyGuardUpgradeable,
UUPSUpgradeable,
IRedemptionQueue
{
using SafeERC20 for IERC20;
/// @dev LAYOUT-FROZEN: this is an ARRAY element (`requests` below). Array elements
/// are laid out contiguously, so adding/reordering ANY field shifts every
/// existing element on the deployed proxy → total corruption. NEVER extend
/// this struct on an upgrade (unlike mapping-value structs, which are safe to
/// tail-extend). Verify with `forge inspect RedemptionQueue storage-layout`.
struct Request {
address owner; // 160 bits ┐
uint64 requestedAt; // ├─ one slot (160+64+32 = 256): the cooldown clock (ADR-0022)
uint32 epochRequested; // ┘ the epoch the request joined (informational)
uint256 sharesRemaining;
uint256 assetsClaimable;
}
/// @dev Transaction-local G4 pricing session. No quote survives a transaction boundary:
/// one post-fee state selects the batch and one aggregate redemption moves value.
struct PricingBatch {
uint256[] requestIds;
uint256[] shares;
uint256[] quotedAssets;
uint256 count;
uint256 aggregateShares;
uint256 withheld;
uint256 withheldRequestId;
uint256 blockedEligibleAt;
uint8 stopReason;
}
/// @custom:storage-location erc7201:forestroad.storage.RedemptionQueue
struct QueueStorage {
IsUSDfr vault; // sUSDfr
IERC20 usdfr;
IReserveManager reserves;
uint64 epochDuration; // settlement HEARTBEAT cadence (ADR-0022 — not the hold)
uint16 epochLiquidityBps;
uint256 currentEpoch;
uint64 epochEndsAt;
bool settling;
uint256 settlementBudget; // remaining, in USDfr assets
uint256 settlementDistributed; // running total for the EpochClosed event
uint256 head; // first not-fully-filled request
uint256 totalQueuedShares;
Request[] requests;
// ADR-0022 append-only tail-extension (namespaced storage, safe to extend):
uint64 redeemCooldown; // forced per-request hold before a request may settle
// C-1 anti-dust-wedge floor (append-only tail-extension): minimum REALIZED value a
// request must be worth to enter the queue. See `Config.DEFAULT_MIN_REDEMPTION_VALUE`.
uint256 minRedemptionValue;
// AUDIT FIX (C-11, append-only tail-extension): the economic floor a LIVE settlement
// is judged against, captured when that settlement opens so a governance change cannot
// retroactively make a frozen budget unsatisfiable. Zero is a legitimate value (the
// floor is disableable), so there is deliberately no sentinel fallback; the contract is
// fresh-deploy-only under ADR-0030 and carries no in-place upgrade path.
uint256 settlementMinValue;
// G4: append-only identifier for explicit transaction-sized pricing sessions.
uint256 nextPricingSessionId;
}
// keccak256(abi.encode(uint256(keccak256("forestroad.storage.RedemptionQueue")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant QUEUE_STORAGE_LOCATION = 0x6ab51628c59659b156fe1c17eb798f5494ec81abdf0900bd9a414fdd72270800;
/// @dev Hard ceiling on the governance-set `minRedemptionValue` ($100): the floor exists to
/// bar dust, not to gate ordinary redeemers out of the sole exit path, so it can never be
/// raised high enough to do the latter.
uint256 private constant MAX_MIN_REDEMPTION_VALUE = 100e18;
/// @dev AUDIT FIX (Q-01, HIGH) — minimum conservative VALUE a partial fill must leave behind.
/// A partial fill is the only way a request's `sharesRemaining` can become a number the
/// queue did not choose, and `previewRedeem(d) == 0` for every `d` below one asset-wei's
/// worth of shares (the 6-decimal virtual offset makes that window ~1e6 share units at
/// par). A residue inside that window is a permanent wedge: next settlement the head IS
/// the residue, the C-1 value guard fires with the whole position priced at zero, and
/// `Queue_HeadNotRedeemable` reverts `closeEpoch` WHOLESALE — freezing every request
/// behind it, with no cancel/defer path (ADR-0018) and no parameter that cures it.
///
/// 1e12 asset-wei (1e-6 USDfr) is a MARGIN, expressed as a value so it tracks the
/// conservative rate automatically: `previewWithdraw` converts it to shares at the same
/// rate `previewRedeem` will price the next fill at, so the residue is left worth at
/// least 1e12 wei — i.e. 1e12 dead-zone widths, not one. The margin, not merely a
/// nonzero test, is what makes the fix hold over TIME: management-fee shares accrue into
/// `_feeAdjustedSupply()` and push `previewRedeem` DOWN, so a residue that previews to
/// exactly 1 wei today decays to 0 later. At the 200 bps/year fee ceiling this margin
/// survives ~1.4e3 years of accrual; it is only exhausted by a declared senior
/// impairment of 1 - 1e-12 of the vault, which is the total-loss state where stopping
/// loudly is the intended behaviour anyway.
///
/// With a fixed floor-rounded quote q, withholding is q(a+c)-q(a+f), where a is
/// previously selected shares, c is the budget-capped final fill and f its reduced fill.
/// A retained positive fill gives distributed+withheld == q(a+c). If q(f)==0, selection
/// discards f and distributes q(a) instead: the credited value is then at most q(a+c)
/// and at least q(a+c)-1 asset wei. This conservative one-wei difference can refuse a
/// settlement exactly at its floor. No positive distribution means refusal regardless
/// of the credit. QueueWithholdingBoundTest exercises the production selection path.
uint256 private constant MIN_RESIDUE_VALUE = 1e12;
/// @dev Bounds multi-head reachability lookahead inside the sub-share rounding band so
/// `closeEpoch` cannot face an unbounded queue scan while still recognizing valid
/// multi-head Q-01 whole-request completions.
uint256 private constant MAX_CAPACITY_LOOKAHEAD = 64;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/// @notice Initializes the queue; the first epoch opens immediately.
/// @param admin Governance timelock.
/// @param guardian Emergency pauser.
/// @param upgrader Upgrade authority (timelock).
/// @param vault The sUSDfr vault (this contract must be set as its queue).
/// @param usdfr The underlying asset.
/// @param reserves Treasury (stable-liquidity source for the budget).
function initialize(
address admin,
address guardian,
address upgrader,
address vault,
address usdfr,
address reserves
) external initializer {
if (
admin == address(0) || guardian == address(0) || upgrader == address(0) || vault == address(0)
|| usdfr == address(0) || reserves == address(0)
) revert Queue_ZeroAddress();
__AccessControl_init();
__Pausable_init();
__ReentrancyGuard_init();
__UUPSUpgradeable_init();
_grantRole(DEFAULT_ADMIN_ROLE, admin);
_grantRole(Roles.GUARDIAN_ROLE, guardian);
_grantRole(Roles.UPGRADER_ROLE, upgrader);
QueueStorage storage $ = _storage();
$.vault = IsUSDfr(vault);
$.usdfr = IERC20(usdfr);
$.reserves = IReserveManager(reserves);
$.epochDuration = Config.DEFAULT_EPOCH_DURATION;
$.epochLiquidityBps = Config.DEFAULT_EPOCH_LIQUIDITY_BPS;
$.redeemCooldown = Config.DEFAULT_REDEEM_COOLDOWN;
$.minRedemptionValue = Config.DEFAULT_MIN_REDEMPTION_VALUE;
$.currentEpoch = 1;
$.epochEndsAt = uint64(block.timestamp) + Config.DEFAULT_EPOCH_DURATION;
emit EpochDurationSet(Config.DEFAULT_EPOCH_DURATION);
emit EpochLiquidityBpsSet(Config.DEFAULT_EPOCH_LIQUIDITY_BPS);
emit RedeemCooldownSet(Config.DEFAULT_REDEEM_COOLDOWN);
emit MinRedemptionValueSet(Config.DEFAULT_MIN_REDEMPTION_VALUE);
}
// ── User paths ───────────────────────────────────────────────────────
/// @inheritdoc IRedemptionQueue
function requestRedeem(uint256 shares) external nonReentrant whenNotPaused returns (uint256 requestId) {
if (shares == 0) revert Queue_ZeroAmount();
QueueStorage storage $ = _storage();
// Queue admission must value shares after all accrued protocol fees. Otherwise a
// requester could lock in a pre-fee minimum-value check and push the liability onto
// holders who remain outside the queue.
$.vault.accrueFees();
// AUDIT FIX (N-1, extended for C-1): a request must be worth at least
// `minRedemptionValue` (default $1, i.e. 1e18) of REALIZED USDfr to enter the queue. Two
// reasons, one gate:
// • anti-griefing: a pure-dust request fills for ~0, takes a FIFO slot ahead of real
// redeemers, and wastes keeper gas.
// • C-1 anti-wedge (anti-griefing, NOT a hard guarantee): `closeEpoch` never burns a
// position worth zero at the conservative mark — it STOPS there (loud
// `Queue_HeadNotRedeemable`), so a sub-wei head would otherwise block the real
// positions behind it. This floor gates the REALIZED rate, so it does NOT by itself
// bound the CONSERVATIVE-rate value that triggers the stop — a large DECLARED
// (unrealized) impairment can still price a legally-entered head to 0 conservative
// while a materially larger position behind it stays redeemable. But that wedge is
// bounded and self-resolving: the blocked large redeemer would only ever settle at a
// near-total-loss conservative price anyway, and the halt clears when the mark cures
// or realizes. The floor keeps CHEAP griefing (a $0-cost dust head) off the table; it
// is not claimed to make the conservative-rate wedge impossible.
// ADR-0022 note: deliberately the REALIZED rate (`convertToAssets`), not the conservative
// redemption rate. This is an anti-griefing filter, not a pricing decision — under a
// declared (unrealized) impairment the conservative rate values requests far below their
// realized worth, and gating on it would lock users out of the queue exactly when they
// most want to join it.
uint256 realizedValue = $.vault.convertToAssets(shares);
if (realizedValue < $.minRedemptionValue) {
revert Queue_BelowMinRedemption(realizedValue, $.minRedemptionValue);
}
requestId = $.requests.length;
$.requests.push(
Request({
owner: msg.sender,
// ADR-0022: the forced-cooldown clock starts now. `closeEpoch` will not
// settle this request until block.timestamp >= requestedAt + redeemCooldown.
requestedAt: uint64(block.timestamp),
epochRequested: uint32($.currentEpoch),
sharesRemaining: shares,
assetsClaimable: 0
})
);
$.totalQueuedShares += shares;
// custody of the shares moves here: FIFO position is locked in, participation
// accrual stops (ADR-0016 note above)
IERC20(address($.vault)).safeTransferFrom(msg.sender, address(this), shares);
emit RedemptionRequested(requestId, msg.sender, shares, $.currentEpoch);
}
/// @inheritdoc IRedemptionQueue
function claim(uint256 requestId) external nonReentrant returns (uint256 assets) {
QueueStorage storage $ = _storage();
if (requestId >= $.requests.length) revert Queue_UnknownRequest(requestId);
Request storage r = $.requests[requestId];
if (r.owner != msg.sender) revert Queue_NotRequestOwner(requestId, msg.sender);
assets = r.assetsClaimable;
if (assets == 0) revert Queue_NothingClaimable(requestId);
r.assetsClaimable = 0; // effects first — no double-claim
$.usdfr.safeTransfer(r.owner, assets);
emit Claimed(requestId, r.owner, assets);
}
// ── Settlement ───────────────────────────────────────────────────────
/// @inheritdoc IRedemptionQueue
/// @dev AUDIT FIX (D7-01 / starvation mirror): gated on `SETTLEMENT_KEEPER_ROLE`. This call
/// samples `settlementBudget = availableLiquidity()` on the first chunk and RE-READS
/// `availableLiquidity()` on every chunk thereafter. Both reads execute in the caller's
/// transaction, so while this was permissionless an attacker could hold a flash loan
/// across the sample and the fills, or latch a settlement at a chosen moment. A flash
/// loan cannot span two transactions; requiring a role the attacker does not hold means
/// they cannot place this call inside their own transaction at all.
///
/// The modifier ORDER is deliberate: the role check runs BEFORE `whenNotPaused`, so an
/// unauthorized caller always gets `AccessControlUnauthorizedAccount` regardless of pause
/// state, and pause state is not probeable by an unauthorized caller.
///
/// NOT CLOSED by this gate: an attacker may still sandwich the keeper's transaction with
/// REAL (non-flashed) capital held across it. That requires millions genuinely at risk
/// across a block instead of a zero-cost flash loan, and is further closed by submitting
/// the keeper call through a private relay. Also unaffected is the
/// `Queue_HeadNotRedeemable` clamp channel, which fires whoever calls.
///
/// SUPERSEDES ADR-0018 §2. See `Roles.SETTLEMENT_KEEPER_ROLE` for the liveness posture
/// and the two-holder requirement.
function closeEpoch(uint256 maxRequests)
external
onlyRole(Roles.SETTLEMENT_KEEPER_ROLE)
nonReentrant
whenNotPaused
{
if (maxRequests == 0) revert Queue_ZeroAmount();
QueueStorage storage $ = _storage();
uint256 unresolved = $.vault.unresolvedPastDueExposure();
if (unresolved != 0) revert IsUSDfr.SUSDfr_UnresolvedPastDue(unresolved);
// C-01: the same fail-closed predicate protects both junior curator capital and the
// sole senior exit. Existing filled claims remain claimable; only new settlement stops.
if ($.reserves.reserveLossExitsLocked()) revert Queue_ReserveLossSettlementFrozen();
if (!$.settling) {
if (block.timestamp < $.epochEndsAt) revert Queue_EpochNotOver($.epochEndsAt);
// Pending primary cash and a newly requested exit share the same cooldown.
// Report that wait before a zero provisional budget can mask it as no liquidity.
if ($.head < $.requests.length) {
uint256 eligibleAt = uint256($.requests[$.head].requestedAt) + $.redeemCooldown;
if (block.timestamp < eligibleAt) revert Queue_AllInCooldown(eligibleAt);
}
$.settling = true;
$.settlementBudget = availableLiquidity();
$.settlementDistributed = 0;
// AUDIT FIX (C-11): capture the economic floor alongside the budget, so a live
// settlement is judged against the parameters it opened under. Raising
// `minRedemptionValue` mid-settlement would otherwise make the guards below
// unsatisfiable against a budget that is already frozen and can only shrink —
// the RC-01 dead end, reachable through a governance setter instead of a chunk
// boundary. A change now takes effect on the NEXT settlement.
$.settlementMinValue = $.minRedemptionValue;
}
// H-04: a live cap can only shrink the remaining epoch budget. The pricing session
// below is transaction-sized, so one read covers its one aggregate redemption.
uint256 liveCap = availableLiquidity();
if ($.settlementBudget > liveCap) $.settlementBudget = liveCap;
// G4/M-2: prepare the optional yield stream against the FULL remaining settlement
// outflow, never the keeper-selected `maxRequests`. This runs before every preview and
// performs the one meaningful fee checkpoint for the chunk. When the front is still in
// cooldown there is no pending outflow yet, so retain the ordinary fee checkpoint
// without recognizing stream value prematurely.
if ($.head < $.requests.length && block.timestamp >= uint256($.requests[$.head].requestedAt) + $.redeemCooldown)
{
$.vault.prepareRedemptionPricing($.settlementBudget);
} else {
$.vault.accrueFees();
}
// G4: selection is a quote-only phase. Every selected request sees the same prepared,
// post-fee numerator and denominator; exactly one vault redemption realizes the batch.
PricingBatch memory batch = _selectPricingBatch($, maxRequests);
if (batch.withheld != 0) {
// A withheld head may have no selected fill; name that head, not the last fill.
emit SettlementWithheld($.currentEpoch, batch.withheldRequestId, batch.withheld);
}
if (batch.aggregateShares != 0) _executePricingBatch($, batch);
uint8 stopReason = batch.stopReason;
uint256 withheld = batch.withheld;
uint256 blockedEligibleAt = batch.blockedEligibleAt;
// settlement completes when the queue is drained, the budget ran out (stopReason 1 —
// including the C-1 budget-blocked zero-value fill), the settlement front is not
// redeemable for any nonzero amount (stopReason 3), or the head is still cooling down
// (stopReason 2). A bare maxRequests stop mid-queue leaves stopReason 0 and keeps the
// settlement open for the next chunk.
bool drained = $.head >= $.requests.length;
// RC-01 / 275a7409: a bare maxRequests stop commits the remaining budget and floor.
// Nominal budget alone is insufficient: converting it to shares and back can lose
// one asset wei, making a later close miss the captured floor. Refuse that state
// before committing the chunk, so a retry can re-snapshot genuinely larger liquidity.
// In the sub-share rounding band, simulate forward across queued heads up to
// `MAX_CAPACITY_LOOKAHEAD` using `_safeBatchFill` so valid multi-head Q-01 whole-request
// completions are admitted without weakening dust rules or risking unbounded gas.
// A later economic/mark change can still affect an already open settlement. This is
// a current-price reachability check, not a promise about future valuations.
if (
!drained && stopReason == 0 && $.settlementDistributed < $.settlementMinValue
&& !_canReachSettlementFloor($, $.settlementMinValue - $.settlementDistributed)
) {
revert Queue_NoLiquidity();
}
// AUDIT FIX (A1, permissionless DoS): do NOT burn the heartbeat window on a
// settlement that distributed NOTHING while requests are still queued. Otherwise
// anyone resets the clock by atomically zeroing idle liquidity (redeem → snapshot
// 0-budget → advance → re-mint), starving the sole sUSDfr exit path. ADR-0022
// extends this to the cooldown: a queue whose head is still cooling down also has
// nothing to settle yet — abandon without advancing, leaving epochEndsAt untouched
// so the request settles the instant its cooldown elapses (no compounding with the
// heartbeat). Both cases: !drained and less than one request's minimum economic
// value distributed → abandon and roll back, don't advance. This also prevents a
// dust-sized partial fill from consuming the heartbeat. A drained queue may still
// close after paying its final dust tail.
if (drained || stopReason != 0) {
if (!drained && ($.settlementDistributed == 0 || $.settlementDistributed + withheld < $.settlementMinValue))
{
$.settling = false;
$.settlementBudget = 0;
if (stopReason == 2) revert Queue_AllInCooldown(blockedEligibleAt);
// C-1 remediation: distinguish "no money" from "the front of the queue cannot be
// redeemed for a nonzero amount at the current mark". Monitoring must be able to
// tell them apart — the second is a valuation state that only clears when the
// mark cures, and `headValuation()` reports it without sending a transaction.
// (stopReason 3 implies `$.head` still indexes a live request: it is only set
// from inside the loop body, which requires `$.head < $.requests.length`.)
if (stopReason == 3) revert Queue_HeadNotRedeemable($.head, $.requests[$.head].sharesRemaining);
revert Queue_NoLiquidity();
}
uint256 closedEpoch = $.currentEpoch;
uint256 distributed = $.settlementDistributed;
uint256 unspent = $.settlementBudget;
$.settling = false;
$.settlementBudget = 0;
$.settlementDistributed = 0;
$.currentEpoch = closedEpoch + 1;
$.epochEndsAt = uint64(block.timestamp) + $.epochDuration;
emit EpochClosed(closedEpoch, distributed + unspent, distributed, $.epochEndsAt);
}
}
// ── Governance ───────────────────────────────────────────────────────
/// @inheritdoc IRedemptionQueue
function setEpochDuration(uint64 duration) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (duration == 0) revert Queue_BadParams();
_storage().epochDuration = duration;
emit EpochDurationSet(duration);
}
/// @inheritdoc IRedemptionQueue
function setEpochLiquidityBps(uint16 bps) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (bps == 0 || bps > Config.BPS) revert Queue_BadParams();
_storage().epochLiquidityBps = bps;
emit EpochLiquidityBpsSet(bps);
}
/// @inheritdoc IRedemptionQueue
/// @dev ADR-0022 forced hold. Applies uniformly to in-flight requests (eligibility is
/// recomputed against the current value), so FIFO-monotonicity is preserved; a
/// change should be timelocked. The configured value must remain between
/// `DEFAULT_REDEEM_COOLDOWN` and `MAX_REDEEM_COOLDOWN`: shortening below the default or
/// disabling the hold would let a queued exit settle before the past-due mark fully ramps.
function setRedeemCooldown(uint64 cooldown) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (cooldown < Config.DEFAULT_REDEEM_COOLDOWN || cooldown > Config.MAX_REDEEM_COOLDOWN) {
revert Queue_BadParams();
}
_storage().redeemCooldown = cooldown;
emit RedeemCooldownSet(cooldown);
}
/// @inheritdoc IRedemptionQueue
/// @dev C-1 anti-dust-wedge floor. Timelocked governance only. Capped at
/// `MAX_MIN_REDEMPTION_VALUE` so it can never be set high enough to lock ordinary
/// redeemers out of the sole exit path. Zero is permitted (disables the floor) but is a
/// deliberate governance act — it re-exposes the sub-wei dust-wedge surface.
///
/// AUDIT FIX (Q-01 round 3): the range has a HOLE at `(0, MIN_RESIDUE_VALUE)`, and the
/// hole is deliberate — do not "simplify" it to a single `>=` bound.
/// • 0 stays legal, but NOT because the abandon guard goes quiet — an earlier draft of
/// this note claimed that, reasoning only about the `distributed < minValue` test,
/// and it is wrong. The guard is
/// `settlementDistributed == 0 || settlementDistributed + withheld < settlementMinValue`.
/// At a zero floor the second conjunct is `X < 0`, false for every uint, so the guard
/// can fire ONLY through the FIRST conjunct — which is floor-independent and, by
/// design, uncreditable. A sub-margin sole head therefore gets a wholesale
/// `Queue_NoLiquidity` where the pre-fix build paid it a slice. That is curable by
/// liquidity (the head is then paid in FULL) and a zero floor is a deliberate
/// non-default governance act, so it is tolerated — see `settlementMinValue`'s C-11
/// note. It is tolerated on those grounds, not because the guard cannot bite.
/// Record this consequence in the parameter-change runbook before disabling the floor.
/// • `>= MIN_RESIDUE_VALUE` is safe because the most the Q-01 branch can withhold from a
/// settlement is `MIN_RESIDUE_VALUE`, and the abandon guard credits exactly that back.
/// • Strictly between them, the withholding can exceed the whole floor, so the credit
/// can no longer guarantee that a deliberate withholding is not itself the reason a
/// settlement misses it. That band is refused rather than left to reason about.
/// Raising the lower bound to `MIN_RESIDUE_VALUE` outright would remove a documented
/// governance capability and break the existing zero-floor tests, including the Q-01 cure
/// sweep that proves no parameter rescues an already-wedged queue.
function setMinRedemptionValue(uint256 value) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (value > MAX_MIN_REDEMPTION_VALUE) revert Queue_BadParams();
if (value != 0 && value < MIN_RESIDUE_VALUE) revert Queue_BadParams();
_storage().minRedemptionValue = value;
emit MinRedemptionValueSet(value);
}
// ── Guardian ─────────────────────────────────────────────────────────
/// @notice Pauses new requests and settlement. Already-settled claims remain available.
/// Emergency use only.
function pause() external onlyRole(Roles.GUARDIAN_ROLE) {
_pause();
}
/// @notice Unpauses.
function unpause() external onlyRole(Roles.GUARDIAN_ROLE) {
_unpause();
}
// ── Views ────────────────────────────────────────────────────────────
/// @inheritdoc IRedemptionQueue
function currentEpoch() external view returns (uint256) {
return _storage().currentEpoch;
}
/// @inheritdoc IRedemptionQueue
function epochEndsAt() external view returns (uint64) {
return _storage().epochEndsAt;
}
/// @inheritdoc IRedemptionQueue
function isSettling() external view returns (bool) {
return _storage().settling;
}
/// @inheritdoc IRedemptionQueue
function settlementBudgetRemaining() external view returns (uint256) {
return _storage().settlementBudget;
}
/// @inheritdoc IRedemptionQueue
function pricingSessionCount() external view returns (uint256) {
return _storage().nextPricingSessionId;
}
/// @inheritdoc IRedemptionQueue
function redeemCooldown() external view returns (uint64) {
return _storage().redeemCooldown;
}
/// @inheritdoc IRedemptionQueue
function minRedemptionValue() external view returns (uint256) {
return _storage().minRedemptionValue;
}
/// @inheritdoc IRedemptionQueue
function eligibleToSettleAt(uint256 requestId) external view returns (uint256) {
QueueStorage storage $ = _storage();
if (requestId >= $.requests.length) revert Queue_UnknownRequest(requestId);
return uint256($.requests[requestId].requestedAt) + $.redeemCooldown;
}
/// @inheritdoc IRedemptionQueue
/// @dev Qualified canonical-USDC liquidity, scaled by the governance share. Primary cash
/// qualifies after the existing 21-day cooldown; verified protocol receipts qualify
/// immediately. Fresh primary deposits cannot lift this live SNAPSHOT
/// used as a per-epoch throughput cap — it does NOT reserve or escrow any stable
/// (see the contract header, R2-M-01). It can move between the snapshot and any
/// claimant's later USDfr→stable conversion.
function availableLiquidity() public view returns (uint256) {
QueueStorage storage $ = _storage();
return Math.mulDiv($.reserves.settlementLiquidity(), $.epochLiquidityBps, Config.BPS);
}
/// @inheritdoc IRedemptionQueue
function request(uint256 requestId)
external
view
returns (
address owner,
uint256 sharesRemaining,
uint256 assetsClaimable,
uint256 epochRequested,
uint256 requestedAt
)
{
QueueStorage storage $ = _storage();
if (requestId >= $.requests.length) revert Queue_UnknownRequest(requestId);
Request storage r = $.requests[requestId];
return (r.owner, r.sharesRemaining, r.assetsClaimable, r.epochRequested, r.requestedAt);
}
/// @inheritdoc IRedemptionQueue
function totalRequests() external view returns (uint256) {
return _storage().requests.length;
}
/// @inheritdoc IRedemptionQueue
function head() external view returns (uint256) {
return _storage().head;
}
/// @inheritdoc IRedemptionQueue
function totalQueuedShares() external view returns (uint256) {
return _storage().totalQueuedShares;
}
/// @notice Wired module addresses (post-deploy validation aid).
function modules() external view returns (address vault, address usdfr, address reserves) {
QueueStorage storage $ = _storage();
return (address($.vault), address($.usdfr), address($.reserves));
}
/// @notice C-1 remediation: conservative-NAV valuation of the settlement front, so a
/// `Queue_HeadNotRedeemable` block is OBSERVABLE off-chain and can never be mistaken
/// for a silent stall. `headValue == 0` with `headShares > 0` is exactly the state in
/// which settlement stops loudly; it clears when the declared senior impairment is
/// cured or realized. `bookValue` shows whether the queue as a whole is redeemable.
/// @return requestId The current head (== `totalRequests()` when the queue is empty).
/// @return headShares The head's unfilled shares (0 when the queue is empty).
/// @return headValue The head's whole remaining position at the conservative redemption NAV.
/// @return bookValue Every queued share at the conservative redemption NAV.
function headValuation()
external
view
returns (uint256 requestId, uint256 headShares, uint256 headValue, uint256 bookValue)
{
QueueStorage storage $ = _storage();
requestId = $.head;
headShares = requestId < $.requests.length ? $.requests[requestId].sharesRemaining : 0;
headValue = $.vault.previewRedeem(headShares);
bookValue = $.vault.previewRedeem($.totalQueuedShares);
}
/// @notice Current epoch parameters.
function epochParams() external view returns (uint64 duration, uint16 liquidityBps) {
QueueStorage storage $ = _storage();
return ($.epochDuration, $.epochLiquidityBps);
}
// ── Internals ────────────────────────────────────────────────────────
/// @dev Returns whether the remaining budget can reach `need` in one bounded FIFO continuation
/// at the current quote and timestamp. Walks queued heads up to `MAX_CAPACITY_LOOKAHEAD`
/// via `_safeBatchFill`, stopping immediately on any request still inside `redeemCooldown`
/// (CORR-DELTA-03) or quoting zero conservative assets so a bare `maxRequests` chunk cannot
/// latch `$.settling = true` below `$.settlementMinValue` across a cooling, zero-valued,
/// or sub-share rounding-miss front.
function _canReachSettlementFloor(QueueStorage storage $, uint256 need) private view returns (bool) {
uint256 budget = $.settlementBudget;
if (budget < need) return false;
uint256 budgetShares = $.vault.convertToSharesAtRedemption(budget);
if (budgetShares == 0) return false;
uint256 aggregateShares = 0;
uint256 cursor = $.head;
uint256 end = $.requests.length;
if (end - cursor > MAX_CAPACITY_LOOKAHEAD) end = cursor + MAX_CAPACITY_LOOKAHEAD;
uint256 cooldown = $.redeemCooldown;
while (cursor < end) {
Request storage req = $.requests[cursor];
if (block.timestamp < uint256(req.requestedAt) + cooldown) return false;
uint256 requestedShares = req.sharesRemaining;
(uint256 fillShares,) = _safeBatchFill($, aggregateShares, budgetShares - aggregateShares, requestedShares);
if ($.vault.previewRedeem(fillShares) == 0) return false;
aggregateShares += fillShares;
if ($.vault.previewRedeem(aggregateShares) >= need) return true;
if (aggregateShares >= budgetShares || fillShares != requestedShares) return false;
cursor += 1;
}
return false;
}
/// @dev Selects one FIFO batch against a single immutable-in-transaction quote. The helper
/// does not mutate requests; a failed aggregate redemption therefore cannot leave a
/// partially-accounted batch even before transaction rollback is considered.
function _selectPricingBatch(QueueStorage storage $, uint256 maxRequests)
private
view
returns (PricingBatch memory batch)
{
uint256 remainingRequests = $.requests.length - $.head;
uint256 limit = maxRequests < remainingRequests ? maxRequests : remainingRequests;
batch.requestIds = new uint256[](limit);
batch.shares = new uint256[](limit);
batch.quotedAssets = new uint256[](limit);
if (limit == 0) return batch;
uint256 budgetShares = $.vault.convertToSharesAtRedemption($.settlementBudget);
if (budgetShares == 0) {
batch.stopReason = 1;
return batch;
}
uint256 cursor = $.head;
uint256 cooldown = $.redeemCooldown;
while (batch.count < limit && cursor < $.requests.length) {
Request storage r = $.requests[cursor];
uint256 eligibleAt = uint256(r.requestedAt) + cooldown;
if (block.timestamp < eligibleAt) {
batch.stopReason = 2;
batch.blockedEligibleAt = eligibleAt;
break;
}
uint256 remainingBudgetShares = budgetShares - batch.aggregateShares;
if (remainingBudgetShares == 0) {
batch.stopReason = 1;
break;
}
(uint256 fillShares, uint256 withheld) =
_safeBatchFill($, batch.aggregateShares, remainingBudgetShares, r.sharesRemaining);
batch.withheld = withheld;
batch.withheldRequestId = cursor;
uint256 quotedAssets = $.vault.previewRedeem(fillShares);
if (quotedAssets == 0) {
batch.stopReason = $.vault.previewRedeem(r.sharesRemaining) != 0 ? 1 : 3;
break;
}
batch.requestIds[batch.count] = cursor;
batch.shares[batch.count] = fillShares;
batch.quotedAssets[batch.count] = quotedAssets;
batch.count += 1;
batch.aggregateShares += fillShares;
// Q-01 permits a complete head to cross the nominal floor-rounded share cap when
// the aggregate asset quote still fits the budget. That completion consumes the
// pricing session: subtracting the now-smaller nominal cap on the next iteration
// would underflow, and there is no additional budget-denominated share capacity to
// allocate safely. Stop after recording the valid over-fill.
if (batch.aggregateShares >= budgetShares) {
batch.stopReason = 1;
break;
}
if (fillShares != r.sharesRemaining) {
batch.stopReason = 1;
break;
}
cursor += 1;
}
}
/// @dev Q-01 residue policy expressed on the aggregate quote. Completing above the nominal
/// share cap is permitted only when the completed aggregate still fits the asset budget.
function _safeBatchFill(
QueueStorage storage $,
uint256 aggregateShares,
uint256 remainingBudgetShares,
uint256 requestedShares
) private view returns (uint256 fillShares, uint256 withheld) {
fillShares = requestedShares < remainingBudgetShares ? requestedShares : remainingBudgetShares;
if (fillShares == requestedShares) return (fillShares, 0);
uint256 minResidue = $.vault.previewWithdraw(MIN_RESIDUE_VALUE);
if (requestedShares - fillShares >= minResidue) return (fillShares, 0);
uint256 completedAggregate = aggregateShares + requestedShares;
uint256 completedQuote = $.vault.previewRedeem(completedAggregate);
// Owner ruling, 22 Nov 2026: retain Q-01's zero-fragment dust protection.
// Only a positive, fully priced rounding tail after an earlier aggregate fill may
// bypass the nominal-fragment predicate. A marked-down whole position keeps it.
bool pricedFragment = $.vault.previewRedeem(remainingBudgetShares) != 0;
if (!pricedFragment && aggregateShares != 0) {
uint256 wholeQuote = $.vault.previewRedeem(requestedShares);
pricedFragment = wholeQuote != 0 && wholeQuote == $.vault.convertToAssets(requestedShares);
}
if (pricedFragment && completedQuote != 0 && completedQuote <= $.settlementBudget) {
return (requestedShares, 0);
}
uint256 budgetCappedAggregate = aggregateShares + fillShares;
fillShares = requestedShares > minResidue ? requestedShares - minResidue : 0;
uint256 reducedAggregate = aggregateShares + fillShares;
withheld = $.vault.previewRedeem(budgetCappedAggregate) - $.vault.previewRedeem(reducedAggregate);
}
/// @dev Executes one vault burn for the whole selected pricing session, then assigns the
/// exact receipt at the quote used during selection. Individual floor quotes are paid to
/// every item except the final item, which deterministically receives aggregate rounding
/// dust. Thus claims sum exactly to assets received and no earlier request can subsidize
/// a later request through a second vault price.
function _executePricingBatch(QueueStorage storage $, PricingBatch memory batch) private {
uint256 quotedAggregateAssets = $.vault.previewRedeem(batch.aggregateShares);
if (quotedAggregateAssets > $.settlementBudget) {
revert Queue_PricingBudgetExceeded(quotedAggregateAssets, $.settlementBudget);
}
uint256 pricingAssets = $.vault.redemptionTotalAssets();
uint256 pricingSupply = $.vault.totalSupply();
bytes32 pricingStateHash = keccak256(
abi.encode(
address($.vault),
$.vault.impairmentSource(),
pricingAssets,
pricingSupply,
$.vault.unvestedYield(),
$.vault.lastFeeAccrual()
)
);
uint256 assetsReceived = $.vault.redeem(batch.aggregateShares, address(this), address(this));
if (assetsReceived != quotedAggregateAssets) {
revert Queue_PricingQuoteChanged(quotedAggregateAssets, assetsReceived);
}
_allocateBatchReceipt($, batch, assetsReceived);
$.totalQueuedShares -= batch.aggregateShares;
$.settlementBudget -= assetsReceived;
$.settlementDistributed += assetsReceived;
uint256 sessionId = $.nextPricingSessionId;
if (sessionId == type(uint256).max) revert Queue_PricingSessionExhausted();
sessionId += 1;
$.nextPricingSessionId = sessionId;
emit PricingBatchSettled(
$.currentEpoch,
sessionId,
batch.requestIds[0],
batch.requestIds[batch.count - 1],
pricingAssets,
pricingSupply,
batch.aggregateShares,
assetsReceived,
pricingStateHash
);
}
function _allocateBatchReceipt(QueueStorage storage $, PricingBatch memory batch, uint256 assetsReceived) private {
uint256 allocated;
for (uint256 i = 0; i < batch.count; ++i) {
uint256 requestId = batch.requestIds[i];
if (requestId != $.head) revert Queue_PricingRangeInvalid($.head, requestId);
Request storage r = $.requests[requestId];
uint256 fillShares = batch.shares[i];
uint256 assetsOut = i + 1 == batch.count ? assetsReceived - allocated : batch.quotedAssets[i];
if (assetsOut == 0 || allocated + assetsOut > assetsReceived) {
revert Queue_PricingAllocationMismatch(assetsReceived, allocated + assetsOut);
}
r.sharesRemaining -= fillShares;
r.assetsClaimable += assetsOut;
allocated += assetsOut;
emit RequestFilled(requestId, fillShares, assetsOut, $.currentEpoch);
if (r.sharesRemaining == 0) $.head = requestId + 1;
}
if (allocated != assetsReceived) {
revert Queue_PricingAllocationMismatch(assetsReceived, allocated);
}
}
function _authorizeUpgrade(address) internal override onlyRole(Roles.UPGRADER_ROLE) {}
function _storage() private pure returns (QueueStorage storage $) {
assembly {
$.slot := QUEUE_STORAGE_LOCATION
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
struct AccessControlStorage {
mapping(bytes32 role => RoleData) _roles;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;
function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
assembly {
$.slot := AccessControlStorageLocation
}
}
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
AccessControlStorage storage $ = _getAccessControlStorage();
bytes32 previousAdminRole = getRoleAdmin(role);
$._roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (!hasRole(role, account)) {
$._roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (hasRole(role, account)) {
$._roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reinitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
*
* NOTE: Consider following the ERC-7201 formula to derive storage locations.
*/
function _initializableStorageSlot() internal pure virtual returns (bytes32) {
return INITIALIZABLE_STORAGE;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
bytes32 slot = _initializableStorageSlot();
assembly {
$.slot := slot
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.22;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC-1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Pausable
struct PausableStorage {
bool _paused;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;
function _getPausableStorage() private pure returns (PausableStorage storage $) {
assembly {
$.slot := PausableStorageLocation
}
}
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
function __Pausable_init() internal onlyInitializing {
}
function __Pausable_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
PausableStorage storage $ = _getPausableStorage();
return $._paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
emit Unpaused(_msgSender());
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// On the first call to nonReentrant, _status will be NOT_ENTERED
if ($._status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
$._status = ENTERED;
}
function _nonReentrantAfter() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
$._status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165Upgradeable is Initializable, IERC165 {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
lib/openzeppelin-contracts/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)
pragma solidity >=0.8.4;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted to signal this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1967.sol)
pragma solidity >=0.4.11;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC4626.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*/
interface IERC4626 is IERC20, IERC20Metadata {
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/**
* @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
*
* - MUST be an ERC-20 token contract.
* - MUST NOT revert.
*/
function asset() external view returns (address assetTokenAddress);
/**
* @dev Returns the total amount of the underlying asset that is “managed” by Vault.
*
* - SHOULD include any compounding that occurs from yield.
* - MUST be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT revert.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
* through a deposit call.
*
* - MUST return a limited value if receiver is subject to some deposit limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
* - MUST NOT revert.
*/
function maxDeposit(address receiver) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
* call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
* in the same transaction.
* - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
* deposit would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* deposit execution, and are accounted for during deposit.
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
* - MUST return a limited value if receiver is subject to some mint limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
* - MUST NOT revert.
*/
function maxMint(address receiver) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
* same transaction.
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
* would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
* execution, and are accounted for during mint.
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, through a withdraw call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
* called
* in the same transaction.
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* withdraw execution, and are accounted for during withdraw.
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
* through a redeem call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
* in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
* same transaction.
* - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
* redemption would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* redeem execution, and are accounted for during redeem.
* - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}
lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC1822.sol)
pragma solidity >=0.4.16;
/**
* @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.21;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This library provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit IERC1967.Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit IERC1967.AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the ERC-1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit IERC1967.BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/beacon/IBeacon.sol)
pragma solidity >=0.4.16;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, bytes memory returndata) = recipient.call{value: amount}("");
if (!success) {
_revert(returndata);
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
revert(add(returndata, 0x20), mload(returndata))
}
} else {
revert Errors.FailedCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
lib/openzeppelin-contracts/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
src/interfaces/IRedemptionQueue.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title IRedemptionQueue — epoch FIFO exits for sUSDfr (ADR-0010, the QEV analog)
/// @notice The vault's ONLY exit path: capital sits in illiquid amortizing facilities,
/// so sUSDfr redemptions queue and settle at epoch close, strictly FIFO, from
/// a liquidity budget snapshotted per settlement. The §1.3 queue invariants —
/// never distribute more than available liquidity, FIFO holds, no
/// double-claim — are this module's safety spec.
interface IRedemptionQueue {
// ── Events ───────────────────────────────────────────────────────────
event RedemptionRequested(uint256 indexed requestId, address indexed owner, uint256 shares, uint256 epoch);
/// @notice A (possibly partial) fill at settlement: `shares` burned for `assets`.
event RequestFilled(uint256 indexed requestId, uint256 shares, uint256 assets, uint256 epoch);
event Claimed(uint256 indexed requestId, address indexed owner, uint256 assets);
/// @notice A settlement finished and the next epoch opened.
/// @dev AUDIT NOTE (Q-01 round 4): `distributed` MAY now fall below `minRedemptionValue` on a
/// committed settlement, by at most `MIN_RESIDUE_VALUE` (1e-6 USDfr). Before the Q-01
/// fix, `!drained && committed` implied `distributed >= minRedemptionValue` by
/// construction and was checkable from this event alone. It no longer is. Pair this
/// event with `SettlementWithheld` to recompute the abandon predicate off-chain.
event EpochClosed(uint256 indexed epoch, uint256 budget, uint256 distributed, uint64 nextEpochEndsAt);
/// @notice Value the Q-01 residue guard deliberately withheld from a settlement, so that a
/// partial fill could not leave the head with a residue inside the zero-value window.
/// @dev Emitted only when the guard actually reduces a fill. The abandon guard credits this
/// value back, so the on-chain commit test is
/// `settlementDistributed + withheld >= settlementMinValue`. Without this event that
/// predicate is not reconstructable from the log (CLAUDE.md §3.1), because `withheld` is
/// a stack local that never reaches storage.
/// @param epoch The settlement's epoch.
/// @param requestId The head request the value was withheld from.
/// @param value Withheld USDfr value, strictly below `MIN_RESIDUE_VALUE`.
event SettlementWithheld(uint256 indexed epoch, uint256 indexed requestId, uint256 value);
/// @notice One transaction-sized pricing session settled through one aggregate vault burn.
/// @dev `pricingAssets + 1` over `pricingSupply + 10**vault.decimalsOffset()` is the single
/// canonical rate used for selection; the final request receives deterministic floor dust.
event PricingBatchSettled(
uint256 indexed epoch,
uint256 indexed sessionId,
uint256 firstRequestId,
uint256 lastRequestId,
uint256 pricingAssets,
uint256 pricingSupply,
uint256 aggregateShares,
uint256 assetsReceived,
bytes32 pricingStateHash
);
event EpochDurationSet(uint64 duration);
event EpochLiquidityBpsSet(uint16 bps);
/// @notice The forced per-request redemption cooldown was set (ADR-0022).
event RedeemCooldownSet(uint64 cooldown);
/// @notice The C-1 anti-dust-wedge minimum redemption value was set.
event MinRedemptionValueSet(uint256 value);
// ── Errors ───────────────────────────────────────────────────────────
error Queue_ZeroAddress();
error Queue_ZeroAmount();
error Queue_EpochNotOver(uint64 endsAt);
error Queue_NotSettling();
error Queue_UnknownRequest(uint256 requestId);
error Queue_NotRequestOwner(uint256 requestId, address caller);
error Queue_NothingClaimable(uint256 requestId);
error Queue_BadParams();
/// @notice A settlement could distribute nothing while requests are queued: it snapshotted
/// zero distributable liquidity, or the remaining budget could not buy a nonzero
/// slice of the head (C-1, the dust-tail case). The epoch is NOT consumed and no
/// position is burned; retry when liquidity returns.
/// Contrast `Queue_HeadNotRedeemable`, which is a VALUATION block, not a cash one.
error Queue_NoLiquidity();
/// @notice C-1 remediation. The settlement front cannot be redeemed for any nonzero amount
/// at the conservative redemption NAV (ADR-0022) — a declared senior impairment has
/// marked the queued book down below a wei, so there is nothing to pay ANY holder.
/// Settlement stops LOUDLY rather than stalling silently: the epoch is not consumed,
/// no position is burned, and every request keeps its shares and its place. It clears
/// when the mark is cured or realized. `headValuation()` reports the state off-chain.
/// The `minRedemptionValue` entry floor bars a dust head from arising except under a
/// near-total senior loss, so under normal operation this block coincides with the
/// whole senior layer being marked below a wei, not one dust position blocking solvent
/// ones behind it.
/// @param requestId The head request settlement stopped at.
/// @param sharesRemaining Its unfilled shares, untouched.
error Queue_HeadNotRedeemable(uint256 requestId, uint256 sharesRemaining);
/// @notice Every queued request is still within its forced cooldown (ADR-0022) — the
/// heartbeat is NOT consumed; `eligibleAt` is when the head becomes settleable.
error Queue_AllInCooldown(uint256 eligibleAt);
/// @notice The request is worth less than `minRedemptionValue` at the realized rate — rejected
/// (C-1 anti-dust-wedge floor + N-1 anti-griefing). `value` is its realized worth.
error Queue_BelowMinRedemption(uint256 value, uint256 minimum);
/// @notice C-01 shared exit interlock: an objective custody shortfall, persistent arm,
/// adjudicated incident, unabsorbed loss or deficit prevents new senior settlement.
error Queue_ReserveLossSettlementFrozen();
error Queue_PricingQuoteChanged(uint256 quotedAssets, uint256 receivedAssets);
error Queue_PricingBudgetExceeded(uint256 quotedAssets, uint256 remainingBudget);
error Queue_PricingAllocationMismatch(uint256 receivedAssets, uint256 allocatedAssets);
error Queue_PricingRangeInvalid(uint256 expectedRequestId, uint256 actualRequestId);
error Queue_PricingSessionExhausted();
// ── User paths ───────────────────────────────────────────────────────
/// @notice Queues `shares` for redemption (transfers them into queue custody —
/// accrual-bearing participation ends here; see the ADR-0016 note in the
/// implementation). Strict FIFO position; no cancellation (queue-jump
/// gaming is not worth the surface in v1 — ADR-0010). Strict FIFO with no
/// reordering. Reverts `Queue_BelowMinRedemption` if the request is worth less than
/// `minRedemptionValue` (default $1) at the realized rate — the C-1 anti-dust-wedge
/// floor. A head worth < 1 wei at the conservative mark is never burned and never
/// requeued; settlement stops loudly (`Queue_HeadNotRedeemable`) until the mark cures.
/// No cancellation, so ADR-0018 stands.
function requestRedeem(uint256 shares) external returns (uint256 requestId);
/// @notice Transfers the filled USDfr of `requestId` to its owner. Callable by the
/// owner only, any time after (partial) fill; zeroes the claimable amount.
function claim(uint256 requestId) external returns (uint256 assets);
// ── Settlement (KEEPER-GATED — budget rules enforce safety) ──────────
/// @notice Settles the epoch once its end has passed: snapshots the liquidity
/// budget on first call, then fills requests strictly FIFO (head request
/// may fill partially) until the budget, the queue, or `maxRequests` is
/// exhausted. Call repeatedly to process a long queue; the epoch advances
/// when settlement completes.
/// C-1: a fill is NEVER taken at a price of zero. If the head's whole remainder
/// prices to zero (senior front not redeemable at the conservative mark), settlement
/// stops with `Queue_HeadNotRedeemable` without consuming the epoch or burning
/// anything; the head keeps its FIFO place and settles when the mark cures.
/// @dev Requires `SETTLEMENT_KEEPER_ROLE`; reverts `AccessControlUnauthorizedAccount`
/// otherwise, and does so BEFORE the pause check. Gated because the epoch liquidity
/// budget is a spot read taken inside this call, which made it flash-loan
/// manipulable while permissionless (D7-01). Supersedes ADR-0018 §2.
function closeEpoch(uint256 maxRequests) external;
// ── Governance ───────────────────────────────────────────────────────
/// @notice Sets the epoch cadence. Timelocked governance only.
function setEpochDuration(uint64 duration) external;
/// @notice Sets the share of stable liquidity distributable per settlement.
function setEpochLiquidityBps(uint16 bps) external;
/// @notice Sets the forced per-request redemption cooldown (ADR-0022). Timelocked
/// governance only. Applies uniformly to in-flight requests.
function setRedeemCooldown(uint64 cooldown) external;
/// @notice Sets the C-1 anti-dust-wedge minimum redemption value (realized USDfr).
/// Timelocked governance only; capped so it can never lock ordinary redeemers out.
function setMinRedemptionValue(uint256 value) external;
// ── Views ────────────────────────────────────────────────────────────
/// @notice Current epoch number (starts at 1).
function currentEpoch() external view returns (uint256);
/// @notice When the current epoch can settle.
function epochEndsAt() external view returns (uint64);
/// @notice True while a settlement is in progress (between first and last
/// `closeEpoch` chunk).
function isSettling() external view returns (bool);
/// @notice The liquidity budget remaining in the active settlement (0 when idle).
function settlementBudgetRemaining() external view returns (uint256);
/// @notice Number of completed transaction-sized pricing sessions.
/// @dev Monotone across epoch boundaries; lets monitoring distinguish a deliberate price
/// revision boundary from two prices inside one session.
function pricingSessionCount() external view returns (uint256);
/// @notice What a settlement starting now could distribute: the governance-set
/// share of the treasury's idle canonical-USDC liquidity.
function availableLiquidity() external view returns (uint256);
/// @notice The forced per-request redemption cooldown, in seconds (ADR-0022).
function redeemCooldown() external view returns (uint64);
/// @notice The C-1 anti-dust-wedge minimum redemption value, in realized USDfr (default $1).
function minRedemptionValue() external view returns (uint256);
/// @notice The earliest timestamp at which `requestId` may be settled by `closeEpoch`
/// (its `requestedAt + redeemCooldown`).
function eligibleToSettleAt(uint256 requestId) external view returns (uint256);
/// @notice A request's state.
/// @return owner The requester.
/// @return sharesRemaining Shares still queued (not yet filled).
/// @return assetsClaimable Filled USDfr not yet claimed.
/// @return epochRequested The epoch the request joined.
/// @return requestedAt The timestamp the request was made (the cooldown clock, ADR-0022).
function request(uint256 requestId)
external
view
returns (
address owner,
uint256 sharesRemaining,
uint256 assetsClaimable,
uint256 epochRequested,
uint256 requestedAt
);
/// @notice Total requests ever made.
function totalRequests() external view returns (uint256);
/// @notice Index of the first not-fully-filled request (== totalRequests when the
/// queue is drained).
function head() external view returns (uint256);
/// @notice Total shares currently queued across all requests.
function totalQueuedShares() external view returns (uint256);
}
src/interfaces/IReserveManager.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title IReserveManager
/// @notice Mainnet-v1 treasury for canonical USDC and deployed facility principal.
/// @dev USD values use 18 decimals. USDC amounts use the token's native 6 decimals.
interface IReserveManager {
/// @notice One-time settlement-liquidity initialization has already completed.
error ReserveManager_SettlementLiquidityAlreadyInitialized();
/// @notice An opening allowance cannot exceed the canonical recorded idle reserve.
error ReserveManager_InvalidSettlementOpening(uint256 opening, uint256 idle);
/// @notice Legacy opening allowance was independently reconciled to retained servicing cash.
event SettlementLiquidityInitialized(uint256 openingAssets, bytes32 indexed evidenceHash);
/// @notice A primary inflow begins its exact existing-cooldown qualification period.
event SettlementPrimaryRecorded(uint64 indexed at, uint256 assets);
/// @notice An outflow cancels newest unseasoned primary amounts without resetting older ages.
event SettlementPrimaryCanceled(uint256 assets);
/// @notice Reconstructable settlement-eligibility transition after a measured cash movement.
event SettlementLiquidityAdjusted(uint256 previous, uint256 current);
/// @notice Cash that may enlarge settlement budgets after primary inflows season through the existing cooldown.
function settlementLiquidity() external view returns (uint256);
/// @notice One-time legacy allowance; refuses once the preliminary monitor is enabled.
function initializeSettlementLiquidity(uint256 openingAssets, bytes32 evidenceHash) external;
/// @notice Pinned history terms for the monitored, execution-time-clamped legacy opening.
/// @dev Every value comes from the hash-bound history record and equals the release guard's immutables.
struct MonitoredOpening {
bytes32 monitorEvidence; // Permanent preliminary-monitor genesis commitment.
uint256 pinnedCashOutflows; // Monitor cashOutflows observed at the history pin.
uint256 pinnedProtectedRounding; // Monitor protectedRounding observed at the history pin.
uint256 qualified; // Conservative qualified-cash lower bound at the history pin.
uint256 selected; // Reviewed upper cap on the opening (at most `qualified`).
uint256 buffer; // Physical idle retained outside the opening.
uint256 roundingCreditCap; // Largest post-pin protected rounding credited; zero requires none.
}
/// @notice The legacy monitor at execution is absent, reset or not the one the history pinned.
error ReserveManager_MonitorMismatch();
/// @notice A monitor counter is below its pinned observation.
error ReserveManager_MonitorRegressed(uint256 pinned, uint256 current);
/// @notice Post-pin protected rounding exceeds the reviewed credit cap.
error ReserveManager_RoundingCreditExceeded(uint256 credit, uint256 cap);
/// @notice A monitored opening may credit at most 1e15 of protected rounding.
error ReserveManager_InvalidRoundingCreditCap(uint256 cap);
/// @notice The monitored opening must retain exactly the reviewed 50,000-USDfr buffer.
error ReserveManager_InvalidOpeningBuffer(uint256 buffer);
/// @notice A selected opening cannot exceed its independently qualified history.
error ReserveManager_InvalidMonitoredSelection(uint256 selected, uint256 qualified);
/// @notice An enabled preliminary monitor requires the clamped initialization path.
error ReserveManager_MonitoredOpeningRequired();
/// @notice The execution-time opening: min(selected, qualified - spent, idle - buffer).
event SettlementOpeningClamped(
uint256 selected, uint256 qualified, uint256 spentSincePin, uint256 bufferedIdle, uint256 opening
);
/// @notice Junior capital consumed by native rounding between the history pin and execution.
event PreReleaseRoundingCredited(uint256 pinned, uint256 current, uint256 credit);
/// @notice One-time governed legacy opening clamped at execution from the preliminary monitor.
/// @dev Opens min(selected, qualified - (cashOutflows - pinned), idle - buffer); never reverts on
/// outflows. Records post-pin protected rounding into this reserve's loss-protection record.
function initializeMonitoredSettlementLiquidity(MonitoredOpening calldata terms, bytes32 evidenceHash) external;
/// @notice Current qualified amount and initialization state for migration and monitoring.
function settlementLiquidityStatus() external view returns (bool initialized, uint256 eligible);
/// @notice Recognition or an opening import makes a return to legacy accounting unsafe.
error ReserveManager_LegacyRollbackUnsafe();
/// @notice Refuses a legacy-code rollback once accrual activation or migration has started.
/// @dev Read-only execution guard for a governance batch, not authority to upgrade.
function requireLegacyRollbackSafe() external view;
/// @notice Canonical USDC was pulled into recorded idle custody.
event USDCDeposited(address indexed from, uint256 requested, uint256 credited);
/// @notice Canonical USDC was released from recorded idle custody.
event USDCReleased(address indexed to, uint256 amount);
/// @notice A permissionless observation compared recorded and live USDC custody.
event IdleUSDCObserved(uint256 recorded, uint256 live, uint256 shortfall);
/// @notice An adjudicated custody loss reduced recorded idle backing.
event IdleUSDCWrittenDown(uint256 amount, uint256 remaining);
/// @notice Returned USDC was credited against one arm's written-down recovery capacity.
event RecoveredIdleUSDCCredited(
uint256 indexed armId, uint256 nativeUnits, uint256 value, bytes32 indexed evidenceHash
);
/// @notice A custody loss reduced backing and fixed the supply reduction the cascade must absorb.
event ReserveLossRecognized(
uint256 indexed incidentId, uint256 backingReduction, uint256 surplusAbsorbed, uint256 supplyReductionRequired
);
/// @notice The complete surplus-to-senior allocation of one recognized custody loss.
event ReserveLossAllocated(
uint256 indexed incidentId,
uint256 backingReduction,
uint256 surplusAbsorbed,
uint256 curatorAbsorbed,
uint256 backstopCovered,
uint256 seniorBurned,
uint256 residualDeficit
);
/// @notice The controller used for supply, backing, and loss-burn checks changed.
event LossControllerSet(address indexed previousController, address indexed newController);
/// @notice The ordered custody-cascade and governance timing modules were wired.
event ReserveLossModulesSet(
address indexed curator, address indexed backstop, address indexed vault, address governor, address timelock
);
/// @notice A Guardian created a persistent reserve-loss interlock and evidence commitment.
event ReserveLossArmed(uint256 indexed armId, uint256 indexed incidentId, bytes32 evidenceHash);
/// @notice Governance cancelled an unused arm and disabled future Guardian arms.
event ReserveLossArmCancelled(uint256 indexed armId, bytes32 indexed evidenceHash);
/// @notice Governance cancelled a custody false alarm while retaining all credit marks.
event UnratifiedReserveLossArmCancelled(
uint256 indexed armId, bytes32 indexed evidenceHash, uint256 retainedPrincipalImpairment
);
/// @notice A previously ratified arm must use the incident settlement path.
error ReserveManager_ArmAlreadyRatified(uint256 armId);
/// @notice Governance closed the arm-bound incident and disabled future Guardian arms.
event ReserveLossArmFinalized(uint256 indexed armId, uint256 indexed incidentId, bytes32 indexed evidenceHash);
/// @notice Governance ratified and executed the current objective custody shortfall.
event ReserveLossRatified(
uint256 indexed armId,
uint256 indexed incidentId,
uint256 approvedMaxLoss,
uint256 actualLoss,
bytes32 evidenceHash
);
/// @notice Governance enabled or disabled creation of new Guardian reserve-loss arms.
event GuardianReserveLossArmsEnabled(bool enabled);
/// @notice A custody-loss incident entered the active register under its bound arm.
event ReserveLossIncidentOpened(uint256 indexed incidentId, uint256 indexed armId, bytes32 evidenceHash);
/// @notice The active custody-loss incident left the register.
event ReserveLossIncidentClosed(uint256 indexed incidentId);
/// @notice A cascade changed the latched unabsorbed reserve deficit.
event ReserveDeficitUpdated(uint256 indexed incidentId, uint256 previousDeficit, uint256 currentDeficit);
/// @notice Governance cleared a cured reserve-deficit latch with supporting evidence.
event ReserveDeficitResolved(uint256 previousDeficit, bytes32 evidenceHash);
/// @notice Idle USDC became deployed principal for a facility.
event PrincipalDeployed(uint256 indexed facilityId, uint256 amount);
/// @notice A retained origination fee became additional facility principal.
event FeeCapitalized(uint256 indexed facilityId, uint256 amount);
/// @notice Contractually accrued PIK interest joined a facility's deployed principal.
/// @dev No cash moved and, unlike `FeeCapitalized`, none was retained either.
/// @param facilityId The facility.
/// @param amount 18-decimal value capitalised.
/// @param deployedAfter The facility's deployed principal after the act.
event PikCapitalized(uint256 indexed facilityId, uint256 amount, uint256 deployedAfter);
/// @notice A cash receipt increased idle custody and reduced the stated principal leg.
event PaymentReceived(
uint256 indexed facilityId, address indexed payer, uint256 usdcAmount, uint256 principalReturned
);
/// @notice Realized facility principal was removed from backing.
event PrincipalWrittenDown(uint256 indexed facilityId, uint256 amount);
/// @notice Governance added an evidence-backed conservative facility impairment.
event PrincipalImpairmentRecognized(
uint256 indexed facilityId,
uint256 amount,
uint256 facilityImpairment,
uint256 totalImpairment,
uint256 backingAfter,
bytes32 evidenceHash
);
/// @notice Governance released part of an evidence-backed conservative facility impairment.
event PrincipalImpairmentReleased(
uint256 indexed facilityId,
uint256 amount,
uint256 facilityImpairment,
uint256 totalImpairment,
bytes32 evidenceHash
);
/// @notice A principal write-down consumed the corresponding previously recognized impairment.
event PrincipalImpairmentRealized(
uint256 indexed facilityId, uint256 amount, uint256 facilityImpairment, uint256 totalImpairment
);
/// @notice The retained compatibility loss-absorber binding changed.
event LossAbsorberSet(address indexed previousAbsorber, address indexed newAbsorber);
/// @notice A funder supplied new canonical USDC backing without minting claims.
event Recapitalized(
address indexed funder, uint256 units, uint256 credited, uint256 backingAfter, uint256 deficitOutstanding
);
/// @notice A senior-exit junior draw was added to the historical prepayment ledger.
event ExitPrepaymentRecorded(uint256 amount, uint256 outstanding);
/// @notice A facility loss consumed part of the historical exit-prepayment ledger.
event ExitPrepaymentConsumed(uint256 indexed facilityId, uint256 consumed, uint256 outstanding);
/// @notice A custody loss consumed the surplus backing part of an exit prepayment.
event ExitPrepaymentAbsorbedByCustody(uint256 indexed incidentId, uint256 consumed, uint256 outstanding);
/// @notice Governance permanently bound the borrower-payout policy used before USDC deployment.
event BorrowerPayoutRegistrySet(address indexed registry);
/// @notice Requested USDC value exceeds recorded idle value.
error ReserveManager_InsufficientIdleValue(uint256 requestedValue, uint256 idleValue);
/// @notice Requested principal reduction exceeds the facility's live deployed principal.
error ReserveManager_InsufficientDeployedPrincipal(uint256 facilityId, uint256 requested, uint256 deployed);
/// @notice A value-moving call supplied a zero amount.
error ReserveManager_ZeroAmount();
/// @notice A required account or module address is zero.
error ReserveManager_ZeroAddress();
/// @notice The caller is not an authorised controller or credit depositor.
error ReserveManager_NotDepositor(address caller);
/// @notice A pull expected canonical USDC but received no value.
error ReserveManager_NoValueReceived();
/// @notice The token balance delta differed from the requested USDC transfer.
error ReserveManager_UnexpectedUSDCReceipt(uint256 expected, uint256 received);
/// @notice A legacy idle write-down exceeds recorded idle value.
error ReserveManager_WriteDownExceedsIdle(uint256 amount, uint256 idle);
/// @notice A USDC release or deployment attempted to target the ReserveManager itself.
error ReserveManager_SelfDeployment();
/// @notice An 18-decimal value cannot be represented exactly in native USDC units.
error ReserveManager_ValueNotUSDCExact(uint256 value);
/// @notice The configured custody token does not use canonical USDC's six decimals.
error ReserveManager_InvalidUSDCDecimals(uint8 decimals);
/// @notice A payment allocated more principal than the USDC value actually received.
error ReserveManager_PrincipalExceedsPayment(uint256 principal, uint256 paymentValue);
/// @notice A proposed curator, backstop, vault, or absorber fails its binding contract.
error ReserveManager_InvalidLossAbsorber(address absorber);
/// @notice A proposed controller fails its module and reserve binding contract.
error ReserveManager_InvalidLossController(address controller);
/// @notice A loss layer's reported burn differs from the observed USDfr supply reduction.
error ReserveManager_LossAbsorberContractViolated(uint256 backingReduction, uint256 supplyBurned);
/// @notice Reported cascade allocation does not reconcile to the recognized loss.
error ReserveManager_LossAllocationMismatch(
uint256 expectedSurplus, uint256 reportedSurplus, uint256 expectedAccounted, uint256 reportedAccounted
);
/// @notice The terminal live supply/backing deficit differs from the cascade calculation.
error ReserveManager_PostLossDeficitMismatch(uint256 expectedDeficit, uint256 observedDeficit);
/// @notice A custody incident id has already been consumed.
error ReserveManager_IncidentAlreadyUsed(uint256 incidentId);
/// @notice A new arm or incident cannot replace the currently active incident.
error ReserveManager_IncidentAlreadyActive(uint256 incidentId);
/// @notice A terminal action requires an active custody incident.
error ReserveManager_NoActiveIncident();
/// @notice The supplied custody incident does not match the active incident.
error ReserveManager_IncidentMismatch(uint256 expected, uint256 supplied);
/// @notice The caller lacks the reserve-administration authority required for the live loss path.
error ReserveManager_ReserveLossCallerNotAdmin(address caller);
/// @notice A reserve-loss allocation used an id outside the custody-event namespace.
error ReserveManager_InvalidReserveLossIncident(uint256 incidentId);
/// @notice A cascade was requested without a recognized supply reduction.
error ReserveManager_NoRecognizedReserveLoss();
/// @notice Finalization was attempted while recognized loss remains unallocated.
error ReserveManager_RecognizedLossOutstanding(uint256 amount);
/// @notice Finalization was attempted while live USDC custody remains short.
error ReserveManager_LiveShortfallExists(uint256 nativeUnits);
/// @notice Finalization was attempted while supply still exceeds backing.
error ReserveManager_DeficitStillExists(uint256 recordedDeficit, uint256 observedDeficit);
/// @notice Creation of new Guardian reserve-loss arms is disabled.
error ReserveManager_GuardianArmsDisabled();
/// @notice A new arm cannot replace the currently active arm.
error ReserveManager_ArmAlreadyActive(uint256 armId);
/// @notice An arm-bound action requires an active arm.
error ReserveManager_NoActiveArm();
/// @notice The supplied arm id does not match the active arm.
error ReserveManager_ArmMismatch(uint256 expected, uint256 supplied);
/// @notice Ratification evidence does not match the Guardian's armed commitment.
error ReserveManager_ArmEvidenceMismatch(bytes32 expected, bytes32 supplied);
/// @notice The monotonic arm id space is exhausted.
error ReserveManager_ArmIdExhausted();
/// @notice Ratification found that the objective custody shortfall was already cured.
error ReserveManager_ShortfallCured();
/// @notice The live custody loss exceeds governance's approved maximum.
error ReserveManager_LossExceedsApproval(uint256 actualLoss, uint256 approvedMaxLoss);
/// @notice No physically returned USDC is available for the supplied arm.
error ReserveManager_NoRecoveredUSDC(uint256 armId);
/// @notice Finalization found returned USDC that has not yet been credited.
error ReserveManager_RecoveredUSDCNotCredited(uint256 armId, uint256 nativeUnits);
/// @notice The superseded arbitrary idle-write-down entry is permanently disabled.
error ReserveManager_LegacyPathDisabled();
/// @notice Cancellation would release an interlock while a loss condition remains live.
error ReserveManager_InterlockReleaseForbidden();
/// @notice Loss-module rebinding is forbidden while an arm, incident, shortfall, or deficit is live.
error ReserveManager_ModuleRebindForbidden();
/// @notice The proposed governor and timelock do not expose one coherent live timing path.
error ReserveManager_InvalidGovernanceTiming(address governor, address timelock);
/// @notice An evidence-backed transition supplied the zero evidence hash.
error ReserveManager_ZeroEvidenceHash();
/// @notice A conservative impairment would exceed the facility's remaining face principal.
error ReserveManager_ImpairmentExceedsFace(uint256 facilityId, uint256 requested, uint256 remainingFace);
/// @notice An impairment release exceeds the amount currently recognized for the facility.
error ReserveManager_ImpairmentReleaseExceedsRecognized(uint256 facilityId, uint256 requested, uint256 recognized);
/// @notice The caller is not the retained compatibility loss absorber.
error ReserveManager_NotLossAbsorber(address caller);
/// @notice Recorded idle USDC exceeds live custody, so a protected out-door is closed.
error ReserveManager_IdleCustodyShortfall(uint256 recordedUnits, uint256 liveUnits);
/// @notice A legacy incident nonce is zero or enters the reserved custody namespace.
error ReserveManager_InvalidIncidentNonce(uint256 incidentNonce);
/// @notice Deficit resolution was requested without a recorded deficit.
error ReserveManager_NoReserveDeficit();
/// @notice An incident close requires its recorded deficit to be resolved first.
error ReserveManager_DeficitResolutionRequired(uint256 recordedDeficit);
/// @notice The borrower-payout policy was already bound and cannot be replaced.
error BorrowerPayout_RegistryAlreadySet(address registry);
/// @notice A proposed borrower-payout policy has no compatible code.
error BorrowerPayout_InvalidRegistry(address registry);
/// @notice Loan proceeds may not be directed to this address.
error BorrowerPayout_RecipientNotAllowed(address recipient);
/// @notice Pulls exact canonical USDC from `from` into recorded idle custody.
function depositUSDC(address from, uint256 amount) external returns (uint256 credited);
/// @notice Releases recorded idle USDC through the controller-only redemption path.
function releaseUSDC(address to, uint256 amount) external;
/// @notice Permanently binds the timelock-managed borrower-payout registry.
function setBorrowerPayoutRegistry(address registry) external;
/// @notice The permanent borrower-payout policy, or zero before the required binding.
function borrowerPayoutRegistry() external view returns (address);
/// @notice Permissionlessly checkpoints the objective live-vs-recorded custody shortfall.
/// @dev Observation never changes backing and never moves junior or senior capital.
/// @return shortfall Native six-decimal USDC units missing from custody.
function reconcileIdleUSDC() external returns (uint256 shortfall);
/// @notice Permissionless live-vs-recorded custody observation; never changes accounting.
function observeIdleUSDC() external view returns (uint256 recorded, uint256 live, uint256 shortfall);
/// @notice Native USDC units by which recorded idle custody exceeds the live token balance.
function idleCustodyShortfall() external view returns (uint256);
/// @notice Recorded backing net of any physically observable idle-custody shortfall.
function recognizedBackingValue() external view returns (uint256);
/// @notice Whether an arm, incident, recognized loss, deficit, or live shortfall locks exits.
function custodyLossUnabsorbed() external view returns (bool);
/// @notice Wires the controller used for direct supply/backing and loss-burn checks.
function setLossController(address controller) external;
/// @notice Wires the retained compatibility absorber after verifying its reserve binding.
function setLossAbsorber(address absorber) external;
/// @notice Legacy incident controls retained as non-credit compatibility surfaces while
/// new custody accounting uses the arm-bound ratification path.
function openReserveLossIncident(uint256 incidentNonce, bytes32 evidenceHash)
external
returns (uint256 incidentId);
/// @notice Closes the exact active legacy incident once no deficit remains.
function closeReserveLossIncident(uint256 incidentId) external;
/// @notice Clears a cured legacy reserve-deficit latch with supporting evidence.
function resolveReserveDeficit(bytes32 evidenceHash) external;
/// @notice Canonical USDC held above the amount recorded as idle custody.
function unrecordedUSDC() external view returns (uint256);
/// @notice Wires the ordered custody cascade and its live governance timing sources.
function setReserveLossModules(address curator, address backstop, address vault, address governor, address timelock)
external;
/// @notice Guardian-only persistent interlock created before an amount-bearing proposal.
/// @return armId Monotonic internal id consumed only by an explicit governance terminal action.
/// @return incidentId Structurally bound upper-half custody event id.
function armReserveLossFreeze(bytes32 evidenceHash) external returns (uint256 armId, uint256 incidentId);
/// @notice Governance consumes an unused arm only when the objective shortfall is zero and
/// no adjudicated loss, incident or deficit exists; future Guardian arms stay disabled.
function cancelAndDisable(uint256 expectedArmId, bytes32 evidenceHash) external;
/// @notice Cancels an unratified custody false alarm and disables further guardian arms.
/// @dev Requires accounted custody and no unsettled custody incident or reserve deficit.
/// Independent credit impairment and exit prepayments remain unchanged.
/// @param expectedArmId Exact active arm being cancelled.
/// @param evidenceHash Nonzero commitment to the governance resolution evidence.
function cancelUnratifiedArm(uint256 expectedArmId, bytes32 evidenceHash) external;
/// @notice Governance kill switch for repeated Guardian arms.
function setGuardianReserveLossArmsEnabled(bool enabled) external;
/// @notice Governance ratifies and atomically absorbs the live objective shortfall, bounded
/// by the amount approved in the proposal. Every tranche under an arm reuses its id
/// and must supply the Guardian's exact armed evidence commitment.
function ratifyAndOpen(uint256 expectedArmId, bytes32 evidenceHash, uint256 approvedMaxLoss)
external
returns (uint256 incidentId, uint256 actualLoss);
/// @notice Credits physically returned canonical USDC without minting USDfr, capped by the
/// amount previously written down under `armId`. May execute after incident closure.
function creditRecoveredIdleUSDC(uint256 armId, bytes32 evidenceHash) external returns (uint256 credited);
/// @notice Atomically resolves a cured deficit, closes the arm-bound incident and disables
/// future Guardian arms. It cannot release a shortfall or uncredited returned USDC.
function finalizeAndDisable(uint256 expectedArmId, bytes32 evidenceHash) external;
/// @notice Pulls new canonical USDC backing without minting USDfr claims.
function recapitalize(uint256 amount) external returns (uint256 credited);
/// @notice Controller used for supply, backing, and loss-burn verification.
function lossController() external view returns (address);
/// @notice Ordered curator, backstop, vault, governor, and timelock bindings.
function reserveLossModules()
external
view
returns (address curator, address backstop, address vault, address governor, address timelock);
/// @notice Active custody incident id and its evidence commitment.
function activeReserveLossIncident() external view returns (uint256 incidentId, bytes32 evidenceHash);
/// @notice Whether a custody incident id has already entered the durable register.
function reserveLossIncidentUsed(uint256 incidentId) external view returns (bool);
/// @notice Latched portion of adjudicated custody losses not absorbed by any capital layer.
function reserveDeficit() external view returns (uint256);
/// @notice Current recognized backing reduction and pending cascade requirement.
function recognizedReserveLoss()
external
view
returns (uint256 backingReduction, uint256 surplusAbsorbed, uint256 supplyReductionRequired);
/// @notice Active arm identity, derived incident, armed evidence, and future-arm switch.
function reserveLossArm()
external
view
returns (uint256 armId, uint256 incidentId, bytes32 evidenceHash, bool armsEnabled);
/// @notice Native USDC recovery capacity created by write-downs under one arm.
function reserveLossRecoveryCapacity(uint256 armId) external view returns (uint256 nativeUnits);
/// @notice Retained compatibility absorber bound to this reserve.
function lossAbsorber() external view returns (address);
/// @notice Historical junior prepayment still available for impairment release.
function exitPrepaidAbsorption() external view returns (uint256);
/// @notice Records a senior-exit junior draw in the compatibility prepayment ledger.
function recordExitPrepayment(uint256 amount) external;
/// @notice Consumes prepayment only against recognized impairment for a facility loss.
function consumeExitPrepayment(uint256 facilityId, uint256 loss) external returns (uint256 used);
/// @notice Shared fail-closed interlock consumed by curator withdrawals and queue settlement.
function reserveLossExitsLocked() external view returns (bool);
/// @notice Backwards-compatible semantic alias used by CuratorModule.
function curatorWithdrawalsLocked() external view returns (bool);
/// @notice Converts exact recorded idle USDC into deployed facility principal.
function recordDeployment(uint256 facilityId, address to, uint256 usdcAmount) external;
/// @notice Adds retained origination-fee cash as facility principal without moving custody.
function recordFeeCapitalization(uint256 facilityId, uint256 amount) external;
/// @notice Capitalises accrued PIK interest into a facility's deployed principal. No cash moves.
/// @dev CREDIT_ROLE, and in practice `WaterfallEngine.capitalizePik` alone, which carries every
/// bound. See `ReserveManager.recordPikCapitalization` for why there is no idle check.
/// @param facilityId The facility.
/// @param amount 18-decimal value to capitalise, exact on the USDC grid.
function recordPikCapitalization(uint256 facilityId, uint256 amount) external;
/// @notice Atomically pulls exact USDC and accounts the principal leg.
function recordPayment(uint256 facilityId, address payer, uint256 usdcAmount, uint256 principal)
external
returns (uint256 receivedValue);
/// @notice Removes realized facility principal and consumes its corresponding impairment.
function recordPrincipalWritedown(uint256 facilityId, uint256 amount) external;
/// @notice Records an evidence-backed conservative mark without moving face principal or
/// allocating the loss between capital layers.
function recognizePrincipalImpairment(uint256 facilityId, uint256 amount, bytes32 evidenceHash) external;
/// @notice Reverses a conservative mark, bounded by the amount previously recognized.
function releasePrincipalImpairment(uint256 facilityId, uint256 amount, bytes32 evidenceHash) external;
/// @notice Recorded idle custody expressed as 18-decimal USDfr value.
function idleReserve() external view returns (uint256);
/// @notice Recorded idle custody in native six-decimal USDC units.
function idleUSDC() external view returns (uint256);
/// @notice Aggregate deployed facility principal before conservative impairments.
function deployedPrincipal() external view returns (uint256);
/// @notice Aggregate evidence-backed conservative principal impairment.
function totalPrincipalImpairment() external view returns (uint256);
/// @notice Evidence-backed conservative impairment recorded for one facility.
function principalImpairmentOf(uint256 facilityId) external view returns (uint256);
/// @notice Recorded idle plus deployed principal, net of conservative impairments.
function totalBackingValue() external view returns (uint256);
/// @notice Outstanding receivable face deployed to one facility.
/// @dev Continuous accrual includes earned but unreceived cash and PIK interest.
function deployedTo(uint256 facilityId) external view returns (uint256);
/// @notice Canonical six-decimal USDC token held by the reserve.
function usdc() external view returns (address);
/// @notice Converts native six-decimal USDC units to 18-decimal protocol value.
function normalizeUSDC(uint256 amount) external pure returns (uint256);
/// @notice Converts exact 18-decimal protocol value to native USDC units.
function denormalizeUSDC(uint256 value) external pure returns (uint256);
}
src/interfaces/IsUSDfr.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
/// @title IsUSDfr
/// @notice The yield-bearing ERC-4626 vault over USDfr (ADR-0005). Yield accrues via the
/// assets/shares exchange rate; exits are routed through the epoch redemption
/// queue (ADR-0010) — the vault's instant withdraw/redeem paths are restricted
/// to the queue module.
interface IsUSDfr is IERC4626 {
/// @notice Settlement waits until servicing resolves all reversible past-due marks.
error SUSDfr_UnresolvedPastDue(uint256 exposure);
/// @notice Reversible risk blocking new withdrawals; quotes and existing cash claims remain readable.
function unresolvedPastDueExposure() external view returns (uint256);
/// @notice Caller is not a loss burner of a controller authorized to mint this asset.
error SUSDfr_InvalidLossProtectionSource(address source, address controller);
/// @notice A previously consumed lifetime capital record may never decrease.
error SUSDfr_LossProtectionCounterDecreased(address source, uint256 previous, uint256 current);
/// @notice Actual consumed protection was excluded from the global performance-fee basis.
event LossProtectionBasisCredited(address indexed source, uint256 capital, uint256 highWaterMark);
/// @notice Pulls the caller's cumulative consumed-protection record, crediting only new capital.
/// @dev Restricted to authenticated fee-accounting/loss actors; no amount is caller supplied.
function syncProtectedCapital(address controller) external;
/// @notice Emitted when the redemption queue address is set.
event RedemptionQueueUpdated(address indexed queue);
/// @notice Instant exit attempted by an account other than the redemption queue.
error SUSDfr_QueueOnly();
/// @notice Share movement involving a sanctioned (blocked) party.
error SUSDfr_TransferBlocked(address from, address to);
/// @notice A management-fee rate above the permanent v1 cap was requested.
error SUSDfr_ManagementFeeTooHigh(uint16 requestedBps);
/// @notice A performance-fee rate above the permanent v1 cap was requested.
error SUSDfr_PerformanceFeeTooHigh(uint16 requestedBps);
/// @notice A fee checkpoint was attempted during a transient share update or
/// while a cross-module fee-accounting operation was locked.
error SUSDfr_FeeAccrualReentrant();
/// @notice A two-phase fee-accounting operation was completed by the wrong caller
/// or with the wrong operation type.
error SUSDfr_InvalidFeeOperation(address caller, uint8 expectedKind, uint8 actualKind);
/// @notice Share supply changed during a fee-neutral marked-NAV operation.
error SUSDfr_FeeOperationSupplyChanged(uint256 expectedSupply, uint256 actualSupply);
/// @notice A replacement fee recipient was not marked as a protocol-exempt address.
error SUSDfr_FeeRecipientNotExempt(address recipient);
/// @notice A proposed impairment source has no code or cannot return a uint256 impairment.
error SUSDfr_InvalidImpairmentSource(address source);
/// @notice A source reported less performance-fee impairment than redemption impairment.
error SUSDfr_InvalidPerformanceFeeImpairment(uint256 pendingImpairment, uint256 performanceImpairment);
/// @notice Emergency clearing was requested while the current impairment source is valid.
error SUSDfr_ImpairmentSourceStillReadable(address source);
/// @notice Emergency clearing was requested when no impairment source is configured.
error SUSDfr_NoImpairmentSource();
/// @notice Too little gas was supplied to prove source failure and finish recovery safely.
error SUSDfr_InsufficientImpairmentRecoveryGas(uint256 available, uint256 required);
/// @notice Emitted when the (fail-open) points hook reverted on a share move (P-04 telemetry).
event PointsHookFailed(address indexed from, address indexed to, uint256 value);
/// @notice Protocol fee shares were minted for time-based management fees.
event ManagementFeeAccrued(uint256 elapsed, uint256 feeAssets, uint256 feeShares);
/// @notice Protocol fee shares were minted on marked NAV above the global high-water mark.
event PerformanceFeeAccrued(
uint256 oldHighWaterMark, uint256 newHighWaterMark, uint256 profitAssets, uint256 feeAssets, uint256 feeShares
);
/// @notice A fee-neutral flow adjusted the global high-water mark.
event HighWaterMarkAdjusted(uint256 oldHighWaterMark, uint256 newHighWaterMark);
/// @notice An authorized module checkpointed fees and locked a junior-capacity operation.
event FeeNeutralMarkedNavChangeStarted(address indexed module, uint256 supply);
/// @notice The authorized junior-capacity operation released its checkpoint lock.
event FeeNeutralMarkedNavChangeCompleted(address indexed module, uint256 supply);
/// @notice The WaterfallEngine locked fee checkpoints before delivering senior yield.
event YieldNotificationStarted(address indexed module);
/// @notice Governance cleared a fee-operation lock left behind by a faulty trusted module.
event FeeOperationEmergencyCleared(address indexed module, uint8 indexed operationKind);
/// @notice The queue prepared one settlement chunk against the full remaining settlement
/// outflow bound before taking any price quote.
/// @param maxAssets Maximum USDfr that the live settlement can still distribute.
/// @param projectedHeld Physical USDfr that would remain if that full bound left the vault.
/// @param instantlyRecognized Previously-unvested yield released before pricing.
event RedemptionPricingPrepared(uint256 maxAssets, uint256 projectedHeld, uint256 instantlyRecognized);
/// @notice Timelocked governance changed the prospective annual management-fee rate.
event ManagementFeeSet(uint16 oldFeeBps, uint16 newFeeBps);
/// @notice Timelocked governance changed the prospective global performance-fee rate.
event PerformanceFeeSet(uint16 oldFeeBps, uint16 newFeeBps);
/// @notice Timelocked governance changed the recipient of future vault fee shares.
event VaultFeeRecipientSet(address indexed oldRecipient, address indexed newRecipient);
/// @notice Timelocked governance cleared an unreadable impairment source without checkpointing it.
/// @dev `failureHash` commits to the failed selector and bounded return evidence, or
/// to the semantically invalid pair of impairment values.
event ImpairmentSourceEmergencyCleared(address indexed source, bytes32 failureHash);
/// @notice Current fee-net realized exchange rate: assets per one whole sUSDfr token.
/// @dev Simulates fee shares due at this timestamp even before a checkpoint transaction.
function currentExchangeRate() external view returns (uint256);
/// @notice Crystallizes management and global high-water-mark performance fees.
/// @dev Permissionless. Fee shares mint to `feeRecipient`; no backing assets leave.
/// @return managementShares Shares minted for the time-based management fee.
/// @return performanceShares Shares minted for profit above the high-water mark.
function accrueFees() external returns (uint256 managementShares, uint256 performanceShares);
/// @notice Prepares queue redemption pricing against the live settlement's full remaining
/// outflow bound, then checkpoints fees once against the prepared state.
/// @dev Queue-only. Using the settlement bound rather than the caller-selected request count
/// makes optional-stream recognition independent of keeper chunking (G4/M-2).
/// @param maxAssets Maximum USDfr the settlement can still distribute.
/// @return instantlyRecognized Previously-unvested yield released before pricing.
function prepareRedemptionPricing(uint256 maxAssets) external returns (uint256 instantlyRecognized);
/// @notice Checkpoints fees and locks checkpoints before an authorized junior-capacity change.
/// @dev Must be paired atomically with `endFeeNeutralMarkedNavChange` by the same module.
/// Junior-capacity effects are excluded by the impairment source's independent
/// performance-fee view; this function never infers a capital flow from a NAV re-read.
function beginFeeNeutralMarkedNavChange() external;
/// @notice Releases an authorized junior-capacity operation's checkpoint lock.
/// @dev The caller and share supply must match the opening snapshot.
function endFeeNeutralMarkedNavChange() external;
/// @notice Locks vault fee checkpoints before the WaterfallEngine delivers senior yield.
/// @dev Must be paired atomically with `notifyYield` by the same module.
function beginYieldNotification() external;
/// @notice Clears a fee-operation lock that survived a successful trusted-module call.
/// @dev Timelocked emergency recovery only. Correct module paths open and close their
/// lock atomically, so a persistent lock means the trusted caller is faulty.
function clearStaleFeeOperation() external;
/// @notice Current global performance-fee rate, in basis points of profit.
function performanceFeeBps() external view returns (uint16);
/// @notice Permanent v1 performance-fee ceiling, in basis points.
function maxPerformanceFeeBps() external pure returns (uint16);
/// @notice Current annualized management-fee rate, in basis points.
function managementFeeBps() external view returns (uint16);
/// @notice Permanent v1 management-fee ceiling, in basis points.
function maxManagementFeeBps() external pure returns (uint16);
/// @notice Time basis used to interpret the annual management-fee rate.
function managementFeeYear() external pure returns (uint64);
/// @notice Global post-fee high-water mark, in the same units as `feeExchangeRate`.
function highWaterMark() external view returns (uint256);
/// @notice Gross rate used for HWM accounting after fee-neutral junior-capital credit.
/// @dev Unlike `currentExchangeRate`, this does not simulate pending fee shares. It can be
/// below the redemption-NAV rate while junior capital protects a live impairment.
function feeExchangeRate() external view returns (uint256);
/// @notice Recipient of sUSDfr management/performance fee shares.
function feeRecipient() external view returns (address);
/// @notice Last timestamp through which the management fee was accrued.
function lastFeeAccrual() external view returns (uint64);
/// @notice Sets the prospective management fee. Timelocked governance only.
function setManagementFee(uint16 feeBps) external;
/// @notice Sets the prospective performance fee. Timelocked governance only.
function setPerformanceFee(uint16 feeBps) external;
/// @notice Changes the recipient of future vault fee shares. Timelocked governance only.
function setFeeRecipient(address recipient) external;
/// @notice Clears a configured impairment source only when a bounded read demonstrably fails.
/// @dev Timelocked governance recovery path. It deliberately cannot replace a readable source
/// or install a new source; normal changes must use the checkpointed setter. Any marked-NAV
/// lift is ratcheted fee-free, permanently waiving performance fees embedded in that lift.
function clearUnreadableImpairmentSource() external;
/// @notice Sets or clears the conservative marked-NAV impairment source.
/// @dev Timelocked governance only. A non-zero replacement must pass an ABI read before
/// the old valuation period is checkpointed and the replacement is stored.
function setImpairmentSource(address source) external;
/// @notice Current conservative marked-NAV impairment source, or zero when unwired.
function impairmentSource() external view returns (address);
/// @notice The redemption queue module (sole permitted caller of withdraw/redeem).
function redemptionQueue() external view returns (address);
/// @notice Sets the redemption queue. Only DEFAULT_ADMIN_ROLE (timelocked governance).
function setRedemptionQueue(address queue) external;
/// @notice Recognizes realized senior yield immediately or starts optional vesting (ADR-0023).
/// @dev Called by the WaterfallEngine right after it delivers `amount` USDfr into the
/// vault. Moves no value. With a zero vesting period, recognition and the resulting
/// performance-fee checkpoint complete in the caller's repayment transaction. A
/// non-zero governance setting defers recognition linearly as an optional
/// market-smoothing policy. Gated by CREDIT_ROLE.
/// @param amount The realized yield just delivered into the vault.
function notifyYield(uint256 amount) external;
/// @notice Realized senior yield not yet released into the exchange rate (ADR-0023).
function unvestedYield() external view returns (uint256);
/// @notice The asset base exits price against: realized assets LESS the
/// declared-but-unrealized senior impairment (ADR-0022 Option Y).
/// @dev Always `<= totalAssets()`, so redemption NAV <= deposit NAV.
function redemptionTotalAssets() external view returns (uint256);
/// @notice Shares that `assets` buys at the conservative redemption NAV, rounded DOWN.
/// @dev The floor-rounded counterpart to `previewWithdraw` (which rounds up). The queue caps
/// its settlement budget with this so `previewRedeem(result) <= assets` holds by
/// construction and settlement can never distribute above the budget (CLAUDE.md §1.3).
/// @param assets The budget, in USDfr.
/// @return The largest share count whose conservative redemption value does not exceed `assets`.
function convertToSharesAtRedemption(uint256 assets) external view returns (uint256);
}
src/libraries/Config.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
/// @title Config
/// @notice Single source of truth for token naming and protocol default parameters
/// (brief Part 12: names are final but kept in one module so a rebrand is a
/// single change).
library Config {
// ── Token naming (final per brief Part 12) ──────────────────────────
string internal constant USDFR_NAME = "Forest Road Dollar";
string internal constant USDFR_SYMBOL = "USDfr";
string internal constant SUSDFR_NAME = "Staked Forest Road Dollar";
string internal constant SUSDFR_SYMBOL = "sUSDfr";
string internal constant GROVE_NAME = "Forest Road Grove";
string internal constant GROVE_SYMBOL = "GROVE";
string internal constant SGROVE_NAME = "Staked Forest Road Grove";
string internal constant SGROVE_SYMBOL = "sGROVE";
// ── Collateral class IDs (ADR-0003 as amended: all FIVE live at genesis) ──
uint256 internal constant CLASS_FILM_TAX_CREDITS = 1;
uint256 internal constant CLASS_RENEWABLE_ENERGY = 2;
uint256 internal constant CLASS_LIFE_SCIENCES = 3;
uint256 internal constant CLASS_REAL_ESTATE = 4;
/// @dev Marked-to-market, related-party class (ADR-0015) — distinct margin/
/// liquidation model, NOT the receivable model of classes 1-4.
uint256 internal constant CLASS_DIGITAL_ASSETS = 5;
uint256 internal constant NUM_CLASSES = 5;
// ── Credit-layer defaults (ADR-0004 / ADR-0014; governance-adjustable) ──
/// @dev USD amounts in 18 decimals (USDfr units).
uint256 internal constant DEFAULT_FIRST_LOSS_PER_CLASS = 10_000_000e18;
uint256 internal constant SGROVE_UNBONDING_PERIOD = 21 days;
// Reward streaming window (ADR-0021 / audit R4-EC1): notified rewards drip linearly
// over this period rather than distributing instantly, so rewards accrue in real time
// (Pendle-compatible) and cannot be sandwiched by a deposit-before-harvest. Governance
// tunable via setRewardsDuration, bounded by SGROVE_MAX_REWARDS_DURATION.
uint64 internal constant SGROVE_REWARDS_DURATION = 7 days;
uint64 internal constant SGROVE_MAX_REWARDS_DURATION = 365 days;
// ── Governance defaults (ADR-0013/0021; FR-controlled at launch) ─────
/// @dev Fixed at genesis, minted to the Forest Road treasury (ADR-0013).
uint256 internal constant GROVE_INITIAL_SUPPLY = 1_000_000_000e18;
uint48 internal constant GOV_VOTING_DELAY = 1 days;
/// @dev Fresh Ethereum genesis: owner-approved 2026-09-18; existing proxy settings persist.
uint32 internal constant GOV_VOTING_PERIOD = 2 days;
uint256 internal constant GOV_PROPOSAL_THRESHOLD = 1_000_000e18; // 0.1% of supply
uint256 internal constant GOV_QUORUM_FRACTION = 4; // % of total votes
uint256 internal constant TIMELOCK_MIN_DELAY = 2 days;
/// @dev C-01 reserve-loss pre-arm floor. The live arm duration is derived from the
/// bound Governor and Timelock at arm time and may be longer; this immutable
/// floor prevents a broken or shortened timing dependency from failing open.
uint256 internal constant RESERVE_LOSS_MIN_PREARM_DURATION = 11 days;
uint256 internal constant RESERVE_LOSS_SCHEDULING_SLACK = 1 days;
/// @dev Preserve the original curator pre-arm floor when launch voting is shortened.
/// Longer live governance schedules still extend the derived protection.
uint256 internal constant CURATOR_PRE_ARM_MIN_GOVERNANCE_PATH = 10 days;
/// @dev Protocol fee on distributed interest (waterfall), in bps. Launch default
/// is deliberately modest; governance-adjustable; economic-review item.
uint256 internal constant DEFAULT_PROTOCOL_FEE_BPS = 1_000; // 10% of interest
/// @dev AUDIT FIX (SWEEP-2 S2-F1) — PERMANENT HARD CAP ON THE INTEREST PROTOCOL FEE.
/// DO NOT DELETE AND DO NOT RAISE WITHOUT FOREST ROAD DIRECTION.
///
/// Before this, `WaterfallEngine.setProtocolFee` was bounded only by `Config.BPS` — it was
/// the ONLY fee rate in the protocol with no permanent ceiling, while its three siblings
/// (`setOriginationFee` -> `MAX_ORIGINATION_FEE_BPS`, `sUSDfr.setPerformanceFee` ->
/// `MAX_PERFORMANCE_FEE_BPS`, `setManagementFee` -> `MAX_MANAGEMENT_FEE_BPS`) all carry
/// one and two of those are PUBLISHED to holders (`maxPerformanceFeeBps()`,
/// `maxManagementFeeBps()`) and described here as "permanent in v1". MEASURED: 10,000 bps
/// was accepted and took the ENTIRE senior yield leg (`toVault` 0, `toFee` the whole
/// interest receipt). Because `_routeInterest` takes this fee FIRST, off the same senior
/// income stream the vault's 20% performance cap protects, total capture of senior yield
/// was reachable AROUND a cap the protocol advertises as permanent — and the fee recipient
/// holds plain USDfr, so it is not a cascade layer.
///
/// The LEVEL mirrors `MAX_PERFORMANCE_FEE_BPS` (20%), i.e. 2x the launch default, which
/// is the house convention for "a permanent ceiling with real governance room under it".
/// The level is an economic-review item; the EXISTENCE of the ceiling is not.
uint16 internal constant MAX_PROTOCOL_FEE_BPS = 2_000; // 20% of interest — permanent in v1
/// @dev Protocol-level performance fee on sUSDfr NAV gains above the global,
/// post-fee high-water mark. Launches at 10% and may only be changed
/// prospectively by timelocked governance. The hard cap is permanent in v1.
uint16 internal constant DEFAULT_PERFORMANCE_FEE_BPS = 1_000; // 10% of profit
uint16 internal constant MAX_PERFORMANCE_FEE_BPS = 2_000; // 20% of profit
/// @dev Effective-annual sUSDfr management fee on a 365-day basis. Launches disabled
/// and may only be enabled prospectively by timelocked governance. Fractional
/// periods use geometric retention; the hard cap is permanent in v1.
uint16 internal constant DEFAULT_MANAGEMENT_FEE_BPS = 0;
uint16 internal constant MAX_MANAGEMENT_FEE_BPS = 200; // 2% per 365-day year
uint64 internal constant MANAGEMENT_FEE_YEAR = 365 days;
/// @dev Origination fee charged at facility funding, in bps of principal (OID
/// mechanics: the borrower nets principal minus fee). Market range for the
/// book's verticals is ~1-2% (ADR-0019); per-class governance-adjustable,
/// capped at MAX_ORIGINATION_FEE_BPS; economic-review item.
uint16 internal constant DEFAULT_ORIGINATION_FEE_BPS = 200; // 2% of principal (Forest Road direction)
uint16 internal constant MAX_ORIGINATION_FEE_BPS = 1_000; // 10% hard cap
/// @dev Margin-call cure window for marked-to-market classes (ADR-0015:
/// "hours-to-days"). Governance-adjustable per class; economic-review item.
uint64 internal constant DEFAULT_MARGIN_CURE_WINDOW = 1 days;
// ── Liquidity-layer defaults (ADR-0010/0022; governance-adjustable) ──
/// @dev Settlement HEARTBEAT (ADR-0022): how often `closeEpoch` may run and refresh
/// the liquidity budget. Under the ADR-0022 cooldown model this is NOT the
/// holding period — `DEFAULT_REDEEM_COOLDOWN` is. The heartbeat must be SHORT
/// relative to the cooldown so the effective wait ≈ cooldown (no compounding).
/// Heartbeat/liquidity calibration is an economic-review item (ADR-0022 §X.5).
uint64 internal constant DEFAULT_EPOCH_DURATION = 1 days;
/// @dev Share of the treasury's idle canonical-USDC liquidity a settlement may
/// distribute to the queue PER
/// HEARTBEAT, leaving the remainder for direct USDfr redemptions. Rescaled from
/// the legacy 50%/30-day batch to preserve ~50%/30-day throughput at a 1-day
/// heartbeat (5000/30 ≈ 167). Economic-review item (ADR-0022 §X.5).
uint16 internal constant DEFAULT_EPOCH_LIQUIDITY_BPS = 167; // ~1.67%/day ≈ 50%/30d
/// @dev ADR-0022: forced per-request redemption cooldown. A queued redemption cannot
/// settle until `requestedAt + DEFAULT_REDEEM_COOLDOWN`. Matches
/// `SGROVE_UNBONDING_PERIOD` (21 days) — long enough that a senior cannot exit
/// ahead of a foreseeable loss (front-running / loss-dodge defense).
uint64 internal constant DEFAULT_REDEEM_COOLDOWN = 21 days;
/// @dev AUDIT FIX (SWEEP-2 CSG-F2) — the UPPER bound on `RedemptionQueue.setRedeemCooldown`.
/// The LOWER bound is `DEFAULT_REDEEM_COOLDOWN` itself and is not a separate constant on
/// purpose: the G2W relief ramp in `CollateralRegistry.conservativeSeniorMark` is written
/// against that exact constant, so the floor must BE it — a second constant is a second
/// thing to forget to move (SEAM-1). 180 days is the same order as
/// `SGrove.setUnbondingPeriod`'s `AUDIT FIX (L)` ceiling and exists for the same reason:
/// an unbounded setter can permanently freeze every queued senior exit by fat finger.
uint64 internal constant MAX_REDEEM_COOLDOWN = 180 days;
/// @dev C-1 anti-dust-wedge floor. Minimum REALIZED value (in USDfr, 18 decimals) a
/// redemption request must be worth to enter the queue — $1. `closeEpoch` never burns a
/// position worth zero at the conservative mark; it stops there, so a sub-wei "dust" head
/// could otherwise wedge the queue for the real positions behind it. Barring dust at entry
/// makes that wedge reachable only when the exchange rate has collapsed by >1e18x (a
/// >99.9999999999999999% senior loss), at which point every realistically-sized position
/// is ALSO worth under a wei and halting the queue is the correct behaviour, not griefing.
/// Measured at the REALIZED rate (`convertToAssets`), not the conservative one, so a
/// declared-but-unrealized impairment does not lock new exits out of the queue.
/// Governance-tunable via `RedemptionQueue.setMinRedemptionValue`.
uint256 internal constant DEFAULT_MIN_REDEMPTION_VALUE = 1e18; // 1 USDfr ($1)
// ── Optional senior-yield vesting (ADR-0023; governance-adjustable) ──
/// @dev Realized senior yield may be vested linearly into `sUSDfr.totalAssets()`
/// instead of landing as an instant step. Only ALREADY-REALIZED yield can be
/// streamed — nothing forward-looking is ever pre-credited, so ADR-0002
/// variable-yield pass-through is untouched. Pendle accepts a valid stepwise SY
/// exchange rate; smoothing is an optional market-design control against
/// payment-timing games and abrupt asset-denominated price moves, not a Pendle
/// protocol prerequisite. Forest Road selected instant recognition for launch.
/// Governance may enable a non-zero window prospectively after economic review.
uint64 internal constant DEFAULT_YIELD_VESTING_PERIOD = 0;
/// @dev Hard ceiling on a newly opened stream. The vault also stores an absolute stream
/// deadline that non-zero governance re-tunes and rollovers may shorten but never
/// extend, so alternating settings cannot defer the same realized yield indefinitely.
uint64 internal constant MAX_YIELD_VESTING_PERIOD = 30 days;
/// @notice RAMP POSTURE (Forest Road direction, 2026-07-21): concentration limits are
/// seeded WIDE OPEN so idle deposit capital can be deployed into originations —
/// initially a facility to the digital-assets book — without a concentration
/// dimension blocking it before the book has any diversity to measure.
/// @dev At `BPS` (100%) the admission test `exp > limitBps * base / BPS` reduces to
/// `exp > base`, and no single dimension can exceed the book, so NOTHING BINDS.
/// Two consequences the operator must hold in mind, both stated rather than implied:
/// 1. Concentration TELEMETRY GOES DARK. `isOverConcentrated`, the drift events and
/// `concentrationHeadroom` all measure against the configured limit, so at 100%
/// they report "clean" unconditionally. There is no on-chain early warning while
/// this posture holds; monitoring must come from the `ExposureRecorded` stream.
/// 2. RATCHETING DOWN LATER IS A CLIFF. Limits are ADMISSION control and a standing
/// breach is permitted (a decrease can never be blocked, or a risk limit could
/// veto a loss being realized). So whatever is concentrated when a real limit is
/// set will instantly read as breached and be frozen from further growth until
/// the book grows around it. Set the first real limits AT or slightly above the
/// actual composition at that time, then step down — do not jump straight to the
/// target.
/// `Validate.s.sol` prints an unmissable posture block whenever this is in force, so
/// an unlimited deployment can never produce output identical to a limited one.
uint16 internal constant RAMP_CONCENTRATION_LIMIT_BPS = 10_000; // 100% = unbounded
uint256 internal constant BPS = 10_000;
/// @notice Forward weight, in bps, that an UNATTESTED permissionless past-due mark
/// (`DefaultManager.markPastDue`) carries in the conservative redemption NAV,
/// relative to an ATTESTED declared default. Used as the fallback whenever
/// `DefaultManager`'s governed slot reads zero (see `pastDueWeightBps()`).
/// @dev OWNER DECISION (Forest Road, 2026-08-07): "An unattested, permissionless past-due
/// mark should NOT carry the same forward weight as an attested declared default."
///
/// DERIVED, NOT INVENTED. The protocol already governs an evidence ladder — but only on
/// the marked-to-market side, where the three rungs are per-class registry parameters:
/// - `maxLtvBps` the rung the protocol is willing to be exposed at (healthy);
/// - `marginCallLtvBps` the rung at which a PERMISSIONLESS, REVERSIBLE early warning
/// fires (`marginCall`) — forward impairment weight ZERO, it only
/// starts a cure clock;
/// - `liquidationLtvBps` the terminal rung, where `liquidate` records the FULL
/// outstanding into the impairment pool and `realizeLoss` becomes
/// reachable — forward impairment weight ONE.
/// `markPastDue` is the receivable-side analogue of the MARGIN-CALL rung: permissionless,
/// reversible, early, and strictly BEFORE the terminal attested rung (`declareDefault`).
/// Governance placed that early rung exactly half way along the governed deterioration
/// band. From the mainnet-v1 class-5 tuple in `script/Deploy.s.sol`
/// (maxLtv 5_000, marginCall 6_500, liquidation 8_000):
///
/// (marginCallLtvBps - maxLtvBps) / (liquidationLtvBps - maxLtvBps)
/// = (6_500 - 5_000) / (8_000 - 5_000) = 1_500 / 3_000 = 1/2 = 5_000 bps.
///
/// WHY NOT THE ADVANCE RATE ALONE. `maxLtvBps`/`ltvBps` cannot supply this weight, and the
/// reasoning is recorded here so it is not re-attempted: the advance rate is DEFINED as the
/// break-even recovery on the attested claim face (ClaimBridge documents the denominator as
/// `principal * BPS / ltvBps`). Senior loss is `max(0, principal - recovery)`, so at a
/// recovery equal to the advance rate the loss is identically ZERO — the advance rate
/// derives a weight of 0, which re-opens H-5 and D5-03. Worse, every variant that forces a
/// positive number out of it (haircut on face, re-advance against carried principal) is
/// MONOTONE THE WRONG WAY: it marks a more conservatively underwritten facility harder.
///
/// DO NOT set this to zero (re-opens H-5: a conflicted servicer can sit on a declaration
/// while seniors exit at par) or to `BPS` (restores the defect this constant fixes).
/// `CollateralRegistry.setPastDueWeight` enforces both bounds.
uint256 internal constant DEFAULT_PAST_DUE_WEIGHT_BPS = 5_000; // 50%
/// @notice sUSDfr entry guard (audit H-3 residual): the maximum ratio of the STRANDED,
/// realized-but-unvested yield stream (`sUSDfr.unvestedYield()`) to the DEPOSIT BASE
/// (`sUSDfr.totalAssets()`) that vault entry tolerates before `deposit`/`mint` close as
/// degenerate.
/// @dev THE HAZARD (ADR-0023): the vault physically holds realized yield that vests linearly
/// into `totalAssets()` over a window and is EXCLUDED from `totalAssets()` until it does.
/// Deposits price on `totalAssets()` (OZ's un-overridden `_convertToShares`), so a
/// depositor entering while that stranded stream is large relative to the base buys shares
/// cheaply and then skims a pro-rata slice of the stream as it vests — extracting from the
/// incumbents who funded it. The hazard scales with `unvestedYield() / totalAssets()`, so
/// the guard keys on exactly that ratio.
///
/// CALIBRATION (economic-review item; audit finding #3 re-key from 10 to 3, then audit
/// R16-01). `sUSDfr._capStreamToBase` enforces a retention boundary against the ACTUAL
/// staked base on both sides of the vault: after every yield delivery AND before every
/// queue outflow, at most `1/(K+1)` of physical vault USDfr remains unvested and any
/// excess is recognized immediately. A healthy low-staking vault therefore cannot be
/// closed by receiving a payment that is large relative to deposits (FRV-FS-03), nor by
/// an ordinary settlement shrinking the base under a live stream (RC-03).
/// The guard remains meaningful after a senior write-down, which burns the recognized
/// base while leaving an already-live stream physically present.
///
/// WHY 3 AND NOT 10 (the audit residual). The OLD `K = 10` reopened entry the moment the
/// ratio fell to 10 — with the stranded stream still 10/11 (~91%) of the vault balance —
/// leaving a near-total skim band `(0, 10]` open. It did NOT "close the entire band": near
/// the top of that band a fresh depositor could still skim ~91% of the vault as the stream
/// vested. Dropping to `K = 3` collapses the open band to `(0, 3)`. `K = 3` bounds the
/// excluded stream at the closure point to 3/4 (~75%) of physical vault assets. It is a
/// DIMENSIONLESS ratio, not a wei level, so it holds identically at every vault scale.
///
/// CORRECTION (AUDIT R16-01, HIGH — the previous justification of the open band was
/// FALSE; do not restore it). This comment used to argue that the top of the `(0, K]` band
/// is "only reachable while the withheld stream is a MAJORITY of the vault, an
/// already-catastrophic near-total-write-down state, never a healthy one". That was wrong,
/// and `K` was never what bounded a routine deposit's skim. The FRV-FS-03 inflow leg
/// created exactly that ratio in a HEALTHY vault: the cap retained `K/(K+1)` of the
/// balance, the largest retention the guard tolerates, which parks the vault at precisely
/// `unvestedYield() == K * totalAssets()` — and `_isDegenerate`'s strict `>` left entry
/// OPEN on that point. Servicing payments are sized off book principal, not off live
/// sUSDfr supply, so any payment large relative to the staked base reached it. What bounds
/// the routine skim is the CAP's retention target, now `1/(K+1)`: healthy operation parks
/// at ratio `1/K`, a factor of `K^2` inside this guard, with a minority (25%) of the
/// vault's cash excluded, and the boundary itself is now CLOSED (`>=`). The band between
/// `1/K` and `K` is reachable only through a realized loss or a governance re-pricing of
/// the vesting window.
///
/// Kept a constant rather than a governance-tunable for
/// this pass: like `SUSDFR_MAX_SHARE_PRICE_COLLAPSE`, it is a defensive safety floor, not an
/// operating knob, and adding storage/setter surface to the namespaced vault struct for it
/// is unwarranted complexity here; a future pass may promote it to a governed parameter.
/// See `SUSDfr._isDegenerate` and `SUSDfr._capStreamToBase`.
uint256 internal constant SUSDFR_MAX_STRANDED_YIELD_RATIO = 3;
/// @dev AUDIT R15-01. Vault entry closes once the realized per-share rate has collapsed to
/// below `1 / SUSDFR_DEGENERATE_RATE_DIVISOR` of the stored high-water mark.
///
/// WHY A SECOND BAND IS NEEDED. `SUSDFR_MAX_STRANDED_YIELD_RATIO` above keys on
/// `unvestedYield()`, which is identically zero at the launch instant-recognition policy
/// (`DEFAULT_YIELD_VESTING_PERIOD == 0`). That band therefore cannot fire at launch,
/// leaving only the `totalAssets() == 0` POINT — and one wei of a permissionless USDfr
/// transfer steps off a point. `_isDegenerate`'s own rationale states the hazard is the
/// whole neighbourhood, not the point; this restores the neighbourhood at every vesting
/// setting.
///
/// WHY PAR IS THE REFERENCE. The stored high-water mark was tried first and rejected:
/// `_accrueFees`'s empty-supply branch ratchets it to `(assets + 1) * 1e18` whenever any
/// balance exists while `totalSupply() == 0`, so a pre-seed donation could inflate the
/// hurdle arbitrarily and then permanently close entry through this band. That is
/// harmless while the HWM only suppresses fees, and becomes a brick the moment entry
/// depends on it — the invariant suite caught exactly that. Par is derived from the
/// token's own decimals, is scale-free, and no actor can move it.
///
/// WHY 100. The band must separate a catastrophic collapse from a merely bad year, because
/// closing entry is a governance event: a vault below 1% of its high-water mark is the
/// near-total write-down the guard exists for, while a 50%-drawdown vault stays open to
/// new capital. ECONOMIC-REVIEW ITEM, on the same footing as `K = 3` above — the shape is
/// a safety floor, but the exact multiple is a judgement about when recapitalization must
/// route through governance rather than through an ordinary deposit.
uint256 internal constant SUSDFR_DEGENERATE_RATE_DIVISOR = 100;
}
src/libraries/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.