Skip to content
Verified contractExactBUSL-1.1

PointsModule

Address0xd8e727d9c8cd19e03e2a2bd7baf42fdb447e7d21
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,459,520
Creation transaction
0x9bb599ea31…6142fa92bd

src/PointsModule.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 {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";

import {ComplianceRegistry} from "./ComplianceRegistry.sol";
import {ICuratorModule} from "./interfaces/ICuratorModule.sol";
import {Config} from "./libraries/Config.sol";
import {Roles} from "./libraries/Roles.sol";

/// @title PointsModule — participation points (ADR-0016, as amended 2026-07-14)
/// @notice A non-transferable participation ledger with THREE per-wallet position types,
///         each accruing `B × ∫ m(τ−S) dτ × rate(τ) × mult / (1 day × unit)`:
///         - sUSDfr shares (mult 1×, also earns the vault yield),
///         - USDfr holdings (mult = usdfrMultiplier, in lieu of yield),
///         - curator first-loss capital per class (mult = curatorMultiplier — the most
///           subordinated capital earns the most points; P-01).
///         `m` is the 1.0×→2.0× maturity ramp (patience favored). Accrual is permissionless
///         per wallet and sybil-safe (linear in balance; a fresh wallet resets the ramp).
///
///         ECONOMIC-INTEGRITY HARDENING (points may inform a future GROVE allocation):
///         - Protocol-exempt addresses (vault/queue/reserves/…) never accrue — they custody
///           balances, they are not participants (skips the vault accruing on staked TVL).
///         - Curator first-loss capital DOES accrue, via a dedicated CuratorModule hook,
///           even though the CuratorModule stays compliance-exempt (P-01).
///         - Rate/multiplier changes are NON-RETROACTIVE: they append a rate EPOCH and each
///           position integrates the rate active in each interval since its last checkpoint
///           (P-03), so a change never reprices already-elapsed time.
///         - `reconcile(wallet)` resets a wallet's positions to its LIVE token / curator
///           balances — the fix for exemption-toggle desync (P-02) and for a fail-open hook
///           silently dropping a transition (P-04).
///
///         HONEST FRAMING (binding, brief Part 0.5): points measure contribution. They are
///         NOT a claim on any token; any future utility is discretionary and counsel-gated.
/// @dev Clean-deployment implementation: curator loss hooks always include the post-loss
///      class balance and survival ratio; no legacy migration or one-argument hook exists.
contract PointsModule is Initializable, AccessControlUpgradeable, UUPSUpgradeable {
    uint256 public constant MATURITY_RAMP = 365 days;
    uint256 internal constant WAD = 1e18;
    uint256 internal constant SHARE_UNIT = 1e24; // one whole sUSDfr (offset-6 vault)
    uint256 internal constant USDFR_UNIT = 1e18; // one whole USDfr (and curator USDfr)
    uint256 internal constant BPS = 10_000;
    uint256 internal constant MAX_RATE_PER_UNIT_DAY = 1e9 * 1e18;
    uint32 internal constant MAX_MULTIPLIER_BPS = 200_000; // 20× ceiling (bounds accrual product)

    uint8 internal constant KIND_SHARES = 0; // mult 1×
    uint8 internal constant KIND_USDFR = 1; // mult = usdfrMultiplier
    uint8 internal constant KIND_CURATOR = 2; // mult = curatorMultiplier
    /// @notice Source chain of the supplemental, governance-verified bridged-share ledger.
    uint256 public constant BSC_CHAIN_ID = 56;
    bytes32 internal constant BSC_POINTS_DOMAIN = keccak256("forestroad.bsc-share-points.v1");

    /// @dev A wallet's position in one token stream. Safe-to-extend (mapping-value struct);
    ///      new members are TAIL-APPENDED only (H-03 added `seenLossEpoch`, which packs into
    ///      the previously-unused high 64 bits of the third slot — no reorder, no insert).
    struct Position {
        uint256 balance;
        uint256 accrued;
        uint64 maturityStart;
        uint64 lastAccrual;
        uint32 lastEpochIdx; // rate epoch active at the last checkpoint (P-03)
        uint32 classId; // 0 for shares/USDfr; the class for a curator position (loss-cap key)
        // H-03 (TIME axis): how many of the class's loss events this position has been
        // RECONCILED through. `seenLossEpoch < curatorLossTimes[classId].length` ⇒ the position
        // is FROZEN, durably: it accrues nothing past the first un-reconciled loss instant.
        uint64 seenLossEpoch;
        // ── H-03 (BALANCE/MATURITY axis) — trailing slots, mapping-value struct only ──
        // The cumulative class survival factor this position's cached `balance` has already
        // been diluted by, and the class loss-round it belongs to. `absorbLoss` dilutes every
        // curator in a class EXACTLY pro-rata (shares untouched, pool balance reduced), so the
        // cached balance can be corrected without a per-curator hook. Without this, a curator
        // who topped back up to their PRE-LOSS notional saw `newPosted == cachedBalance`, no
        // `_track` ran, and the replacement capital silently inherited the destroyed capital's
        // maturity ramp — the H-03 harm reached by a second path.
        uint256 seenSurvivalWad; // 0 == WAD (unset)
        uint64 seenLossRound;
    }

    /// @dev A rate epoch: the rate/multipliers active from `start` until the next epoch.
    ///
    ///      AUDIT FIX (G1b): LAYOUT-FROZEN: this is an ARRAY element (`rateEpochs` below) and it
    ///      was the one fixed-stride struct in the protocol carrying no such warning, while
    ///      `SGrove.Unbond` and `RedemptionQueue.Request` both did. Array elements are laid out
    ///      contiguously, so adding, reordering or retyping ANY field changes the stride and
    ///      shifts every epoch after index 0 on the deployed proxy — silently repricing every
    ///      historical accrual interval. NEVER extend this struct on an upgrade; tail-extend the
    ///      namespaced `PointsStorage` root (or a mapping-value struct) instead. Do not delete
    ///      this warning: `tools/check-storage-layout.mjs` now REQUIRES that marker on every
    ///      fixed-stride struct it reaches, and deleting it fails the gate.
    struct RateEpoch {
        uint64 start;
        uint32 usdfrMultBps;
        uint32 curatorMultBps;
        uint256 ratePerUnitDay;
    }

    /// @notice A complete cumulative BSC share-points snapshot, approved by existing Ethereum governance.
    /// @dev Mapping value: extend only at the tail. The evidence commits to complete finalized transfer and rate
    ///      histories, exact Ethereum share-point arithmetic, and holder/supply/backing reconciliation. This is a
    ///      governance-attested historical ledger, not an independently verified BSC light client or a token claim.
    struct BscPointsCheckpoint {
        address token;
        uint64 blockNumber;
        uint64 timestamp;
        bytes32 blockHash;
        bytes32 root;
        bytes32 evidenceHash;
        uint256 cumulativeTotal;
    }

    /// @custom:storage-location erc7201:forestroad.storage.PointsModule
    struct PointsStorage {
        ComplianceRegistry compliance; // protocol-exempt set
        address vault; // sUSDfr — sole caller of onSharesTransfer
        address usdfrToken; // USDfr — sole caller of onUSDfrTransfer
        address curatorModule; // CuratorModule — sole caller of onCuratorStakeChange
        RateEpoch[] rateEpochs; // append-only; index 0 is genesis (P-03)
        mapping(address => Position) sPos; // sUSDfr shares
        mapping(address => Position) uPos; // USDfr
        mapping(address => mapping(uint256 => Position)) cPos; // curator first-loss per class
        uint256 totalTrackedShares;
        uint256 totalTrackedUsdfr;
        uint256 totalTrackedCurator;
        // AUDIT FIX: last time a class absorbed a loss. Retained for observability only — the
        // freeze is driven by the per-loss epoch log below (H-03), because a single overwritable
        // timestamp re-opened the accrual window for positions frozen by an EARLIER loss.
        mapping(uint256 classId => uint64) lastCuratorLossAt;
        // ── H-03 tail extension (append-only; never reorder or insert above this line) ──
        // Append-only, non-decreasing log of the instants at which `classId` absorbed a loss.
        // A curator position is frozen at `curatorLossTimes[classId][p.seenLossEpoch]` — the
        // FIRST loss it has not been reconciled through — so a later loss can never move the
        // freeze instant forward, and a permissionless `checkpoint()` can never step over it.
        mapping(uint256 classId => uint64[]) curatorLossTimes;
        // Class loss ROUND — bumped whenever a loss wipes the class pool to zero, or whenever a
        // loss arrives WITHOUT a usable dilution ratio (a legacy one-argument `onCuratorLoss`,
        // or a migrated pre-upgrade loss). A position whose `seenLossRound` is behind has its
        // cached balance zeroed: nothing about it can be trusted, and `reconcile()` restores it
        // from the live `postedOf`.
        mapping(uint256 classId => uint64) curatorLossRound;
        // Cumulative survival factor within the current loss round, WAD-scaled and monotonically
        // non-increasing (0 == WAD, i.e. no dilution yet this round).
        mapping(uint256 classId => uint256) curatorSurvivalWad;
        // BSC remediation: tail-append only. Keep every legacy position and the frozen RateEpoch array unchanged.
        mapping(uint256 chainId => BscPointsCheckpoint) bscCheckpoints;
        mapping(address wallet => uint256 cumulativePoints) bscCredited;
        uint256 bscTotalCredited;
    }

    // keccak256(abi.encode(uint256(keccak256("forestroad.storage.PointsModule")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant POINTS_STORAGE_LOCATION =
        0x2b0f9b300e42162fe5738c4f7cc02b34c204f066c1bd41ebe399ed932bb31b00;

    event PointsAccrued(address indexed wallet, uint8 indexed kind, uint256 amount);
    event RateEpochAppended(uint256 indexed index, uint256 ratePerUnitDay, uint32 usdfrMultBps, uint32 curatorMultBps);
    event CuratorModuleSet(address indexed curatorModule);
    event Reconciled(address indexed wallet);
    /// @notice Governance approved a finalized-history snapshot; publication itself credits nobody.
    event BscPointsCheckpointApproved(
        address indexed token, uint64 indexed blockNumber, bytes32 root, bytes32 evidenceHash, uint256 cumulativeTotal
    );
    /// @notice A verified cumulative proof credited only the wallet's previously uncredited delta.
    event BscPointsCredited(address indexed wallet, uint64 indexed blockNumber, uint256 delta, uint256 cumulative);
    /// @notice Mistaken token-stream points and cached balances were retired for an exempt protocol custodian.
    event ProtocolCustodyPointsRetired(
        address indexed custody, uint256 sharePoints, uint256 usdfrPoints, uint256 trackedShares, uint256 trackedUsdfr
    );
    /// @notice A class absorbed a loss; every un-reconciled curator position in it freezes at `at`.
    /// @param classId The collateral class that absorbed the loss.
    /// @param lossEpoch The zero-based index of this loss in the class's append-only loss log.
    /// @param at The instant of the loss — the accrual ceiling for positions frozen by it.
    /// @param poolBalanceBefore The class first-loss pool balance before absorption.
    /// @param poolBalanceAfter The class first-loss pool balance after absorption. `before` and
    ///        `after` both zero means the ratio was NOT supplied (legacy/migrated loss), in
    ///        which case every cached balance in the class is distrusted outright.
    event CuratorLossRecorded(
        uint256 indexed classId,
        uint256 indexed lossEpoch,
        uint64 at,
        uint256 poolBalanceBefore,
        uint256 poolBalanceAfter
    );
    /// @notice A curator position was reconciled through every recorded loss and resumed accruing.
    /// @param wallet The curator.
    /// @param classId The collateral class of the thawed position.
    /// @param seenLossEpoch The loss-log length the position is now reconciled through.
    event CuratorPositionThawed(address indexed wallet, uint256 indexed classId, uint64 seenLossEpoch);
    /// @notice A curator position's cached first-loss balance was written down to reflect the
    ///         class losses it had not yet absorbed (the pro-rata dilution `absorbLoss` applied).
    /// @param wallet The curator.
    /// @param classId The collateral class.
    /// @param oldBalance The stale-high cached balance.
    /// @param newBalance The diluted balance (0 when the class pool was wiped, or when the
    ///        dilution ratio was unavailable and the balance therefore cannot be trusted).
    event CuratorBalanceDiluted(
        address indexed wallet, uint256 indexed classId, uint256 oldBalance, uint256 newBalance
    );

    error Points_OnlyVault();
    error Points_OnlyUSDfr();
    error Points_OnlyCurator();
    error Points_ZeroAddress();
    error Points_BadRate(uint256 rate);
    error Points_BadMultiplier(uint32 bps);
    error Points_CuratorModuleAlreadySet();
    /// @notice Checkpoint metadata is missing, invalid or in the future.
    error Points_BadBscCheckpoint();
    /// @notice A checkpoint must advance the finalized source block and never move time backwards.
    error Points_BscCheckpointNotNewer();
    /// @notice An established remote token cannot be replaced by a different token.
    error Points_BscTokenChanged();
    /// @notice The proof does not match the latest approved checkpoint and complete leaf domain.
    error Points_BadBscProof();
    /// @notice The cumulative proof contains no points beyond this wallet's credited watermark.
    error Points_NoNewBscPoints();
    /// @notice Approved cumulative points may not decrease or be exceeded by credits.
    error Points_BscTotalExceeded();
    /// @notice Custody retirement requires an explicit current protocol exemption.
    /// @param custody The address whose token-stream points were proposed for retirement.
    error Points_CustodyNotExempt(address custody);

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    /// @notice Initializes with the genesis rate epoch (1 point/unit/day, USDfr 3×, curator 5×).
    function initialize(address admin, address upgrader, address compliance, address vault, address usdfrToken)
        external
        initializer
    {
        if (
            admin == address(0) || upgrader == address(0) || compliance == address(0) || vault == address(0)
                || usdfrToken == address(0)
        ) revert Points_ZeroAddress();
        __AccessControl_init();
        __UUPSUpgradeable_init();
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        _grantRole(Roles.UPGRADER_ROLE, upgrader);
        PointsStorage storage $ = _storage();
        $.compliance = ComplianceRegistry(compliance);
        $.vault = vault;
        $.usdfrToken = usdfrToken;
        $.rateEpochs.push(
            RateEpoch({
                start: uint64(block.timestamp),
                usdfrMultBps: 30_000,
                curatorMultBps: 50_000,
                ratePerUnitDay: 1e18
            })
        );
        emit RateEpochAppended(0, 1e18, 30_000, 50_000);
    }

    /// @notice Wires the CuratorModule (one-time) so first-loss capital accrues points.
    function setCuratorModule(address module) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (module == address(0)) revert Points_ZeroAddress();
        PointsStorage storage $ = _storage();
        if ($.curatorModule != address(0)) revert Points_CuratorModuleAlreadySet();
        $.curatorModule = module;
        emit CuratorModuleSet(module);
    }

    // ── token / curator hooks (fail-open at the caller) ──────────────────

    /// @notice Called by the sUSDfr vault on every share balance change.
    function onSharesTransfer(address from, address to, uint256 amount) external {
        PointsStorage storage $ = _storage();
        if (msg.sender != $.vault) revert Points_OnlyVault();
        if (amount == 0) return;
        if (from != address(0) && !_excluded($, from)) {
            $.totalTrackedShares -= _untrack($, $.sPos[from], amount, SHARE_UNIT, KIND_SHARES, from);
        }
        if (to != address(0) && !_excluded($, to)) {
            _track($, $.sPos[to], amount, SHARE_UNIT, KIND_SHARES, to);
            $.totalTrackedShares += amount;
        }
    }

    /// @notice Called by USDfr on every balance change (mints, transfers, burns).
    function onUSDfrTransfer(address from, address to, uint256 amount) external {
        PointsStorage storage $ = _storage();
        if (msg.sender != $.usdfrToken) revert Points_OnlyUSDfr();
        if (amount == 0) return;
        if (from != address(0) && !_excluded($, from)) {
            $.totalTrackedUsdfr -= _untrack($, $.uPos[from], amount, USDFR_UNIT, KIND_USDFR, from);
        }
        if (to != address(0) && !_excluded($, to)) {
            _track($, $.uPos[to], amount, USDFR_UNIT, KIND_USDFR, to);
            $.totalTrackedUsdfr += amount;
        }
    }

    /// @notice Called by the CuratorModule when a curator's posted first-loss changes (P-01).
    ///         `newPosted` is the curator's live `postedOf(classId, curator)` after the change;
    ///         the position is reconciled to it (so withdrawals reduce it correctly).
    /// @dev Curators are the beneficiaries (not exempt); first-loss earns at the curator
    ///      multiple even though the CuratorModule itself is compliance-exempt.
    function onCuratorStakeChange(address curator, uint256 classId, uint256 newPosted) external {
        PointsStorage storage $ = _storage();
        if (msg.sender != $.curatorModule) revert Points_OnlyCurator();
        Position storage p = $.cPos[curator][classId];
        p.classId = uint32(classId); // tag the position so _pending applies the loss cap
        // H-03 (BALANCE/MATURITY axis): write the cached balance down by every class loss this
        // position has not yet absorbed BEFORE comparing it to `newPosted`. Otherwise a curator
        // topping back up to their pre-loss notional produced `newPosted == old`, neither
        // `_track` nor `_untrack` ran, and the fresh capital inherited the destroyed capital's
        // maturity ramp — i.e. taking a loss and replacing it out-accrued never taking one.
        _applyCuratorDilution($, p, classId, curator);
        uint256 old = p.balance;
        // H-03: a position with NO cached balance has nothing stale to freeze, so a curator
        // opening (or re-opening) a position from zero starts reconciled through every recorded
        // loss. This is the SECOND path that clears a freeze (see `reconcile`); it is safe
        // because there is no stale capital left to credit, and it emits the thaw so the freeze
        // lifecycle stays reconstructable from events alone.
        if (old == 0 && newPosted != 0) _syncLossWatermark($, p, classId, curator);
        if (newPosted > old) {
            _track($, p, newPosted - old, USDFR_UNIT, KIND_CURATOR, curator);
            $.totalTrackedCurator += newPosted - old;
        } else if (newPosted < old) {
            $.totalTrackedCurator -= _untrack($, p, old - newPosted, USDFR_UNIT, KIND_CURATOR, curator);
        }
    }

    /// @notice Records that `classId` absorbed a loss, WITH the pool balances that bracket the
    ///         absorption (CuratorModule-only). Equal balances are a balance-neutral accounting
    ///         operation, not a loss, and are ignored so representation changes cannot freeze a
    ///         whole class (M-4). For an economic loss, the supplied ratio writes cached balances
    ///         down without a per-curator hook and preserves correct maturity blending on a later
    ///         top-up (H-03).
    /// @param classId The collateral class that absorbed the loss.
    /// @param poolBalanceBefore The class first-loss pool balance immediately before absorption.
    /// @param poolBalanceAfter The class first-loss pool balance immediately after absorption.
    function onCuratorLoss(uint256 classId, uint256 poolBalanceBefore, uint256 poolBalanceAfter) external {
        PointsStorage storage $ = _storage();
        if (msg.sender != $.curatorModule) revert Points_OnlyCurator();
        if (poolBalanceBefore == poolBalanceAfter) return;
        _recordCuratorLoss($, classId, poolBalanceBefore, poolBalanceAfter);
    }

    /// @notice Resets a wallet's positions to its LIVE token/curator balances (P-02/P-04).
    ///         Permissionless and self-correcting: fixes a desync from an exemption toggle or
    ///         a fail-open hook that dropped a transition, and refreshes stale curator
    ///         positions after a loss dilution.
    /// @dev This is the primary path that clears a curator freeze (H-03), and it thaws EVERY
    ///      class at once against the live `postedOf`, so a curator holding several positions
    ///      across several loss events can never end up partially thawed. Accrual over the
    ///      frozen window is forfeited by construction: the cached balance was unverifiable
    ///      there. The only OTHER clear is `onCuratorStakeChange` re-opening a position from a
    ///      zero cached balance, which has no stale capital to credit.
    /// @param wallet The wallet to reconcile (permissionless — anyone may call it for anyone).
    function reconcile(address wallet) external {
        PointsStorage storage $ = _storage();
        bool exempt = _excluded($, wallet);
        _reconcile(
            $, $.sPos[wallet], exempt ? 0 : IERC20($.vault).balanceOf(wallet), SHARE_UNIT, KIND_SHARES, wallet, 0
        );
        _reconcile(
            $, $.uPos[wallet], exempt ? 0 : IERC20($.usdfrToken).balanceOf(wallet), USDFR_UNIT, KIND_USDFR, wallet, 1
        );
        if ($.curatorModule != address(0)) {
            for (uint256 c = 1; c <= Config.NUM_CLASSES; ++c) {
                Position storage cp = $.cPos[wallet][c];
                cp.classId = uint32(c); // tag for the loss cap
                // Write the cached balance down by any un-absorbed class dilution first, so the
                // snap below is an honest delta and `_track` blends maturity on genuinely new
                // capital only.
                _applyCuratorDilution($, cp, c, wallet);
                uint256 target = ICuratorModule($.curatorModule).postedOf(c, wallet);
                // Accrue under the freeze cap FIRST (so the frozen window earns nothing), snap
                // the balance to the live posted amount, and only then clear the freeze.
                _reconcile($, cp, target, USDFR_UNIT, KIND_CURATOR, wallet, 2);
                _thawCurator($, cp, c, wallet);
            }
        }
        emit Reconciled(wallet);
    }

    /// @notice Checkpoints a wallet's positions (harmless anytime; keeps reads warm).
    /// @dev A checkpoint can only ever move a curator position DOWN: it applies any outstanding
    ///      pro-rata loss dilution to the cached balance, and it can NEVER clear a freeze
    ///      (H-03 — the original bypass was exactly a permissionless checkpoint resuming
    ///      accrual on wiped capital).
    function checkpoint(address wallet) external {
        PointsStorage storage $ = _storage();
        _accrue($, $.sPos[wallet], SHARE_UNIT, KIND_SHARES, wallet);
        _accrue($, $.uPos[wallet], USDFR_UNIT, KIND_USDFR, wallet);
        for (uint256 c = 1; c <= Config.NUM_CLASSES; ++c) {
            Position storage cp = $.cPos[wallet][c];
            // Only touch the dilution watermark of a position that actually holds first-loss —
            // otherwise every checkpoint of every wallet would write 2 slots per lossy class.
            if (cp.balance != 0) _applyCuratorDilution($, cp, c, wallet);
            _accrue($, cp, USDFR_UNIT, KIND_CURATOR, wallet);
        }
    }

    // ── governance (rate epochs — non-retroactive, P-03) ─────────────────

    /// @notice Sets the base accrual rate; appends a rate epoch (applies going forward only).
    function setRate(uint256 ratePerUnitDay_) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (ratePerUnitDay_ > MAX_RATE_PER_UNIT_DAY) revert Points_BadRate(ratePerUnitDay_);
        RateEpoch storage cur = _current();
        _appendEpoch(ratePerUnitDay_, cur.usdfrMultBps, cur.curatorMultBps);
    }

    /// @notice Sets the USDfr multiple of the base rate (bps); appends a rate epoch.
    function setUSDfrMultiplier(uint32 multiplierBps) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (multiplierBps == 0 || multiplierBps > MAX_MULTIPLIER_BPS) revert Points_BadMultiplier(multiplierBps);
        RateEpoch storage cur = _current();
        _appendEpoch(cur.ratePerUnitDay, multiplierBps, cur.curatorMultBps);
    }

    /// @notice Sets the curator first-loss multiple (bps); appends a rate epoch.
    function setCuratorMultiplier(uint32 multiplierBps) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (multiplierBps == 0 || multiplierBps > MAX_MULTIPLIER_BPS) revert Points_BadMultiplier(multiplierBps);
        RateEpoch storage cur = _current();
        _appendEpoch(cur.ratePerUnitDay, cur.usdfrMultBps, multiplierBps);
    }

    // ── BSC historical share points (existing governance only; no new signer or mint authority) ──

    /// @notice Approves cumulative BSC points earned under the same rate/maturity rules as Ethereum share points.
    /// @dev Only the existing upgrade/governance role may attest a root. A new root cannot switch source tokens,
    ///      move backward in source block/time or reduce total earned points. It must bind a reviewable evidence
    ///      hash; actual history verification happens before governance approval, not inside this contract.
    function approveBscPointsCheckpoint(BscPointsCheckpoint calldata checkpoint_)
        external
        onlyRole(Roles.UPGRADER_ROLE)
    {
        if (
            checkpoint_.token == address(0) || checkpoint_.blockNumber == 0 || checkpoint_.timestamp == 0
                || checkpoint_.timestamp > block.timestamp || checkpoint_.blockHash == bytes32(0)
                || checkpoint_.root == bytes32(0) || checkpoint_.evidenceHash == bytes32(0)
        ) revert Points_BadBscCheckpoint();
        PointsStorage storage $ = _storage();
        BscPointsCheckpoint storage previous = $.bscCheckpoints[BSC_CHAIN_ID];
        if (checkpoint_.blockNumber <= previous.blockNumber || checkpoint_.timestamp < previous.timestamp) {
            revert Points_BscCheckpointNotNewer();
        }
        if (previous.token != address(0) && checkpoint_.token != previous.token) revert Points_BscTokenChanged();
        if (checkpoint_.cumulativeTotal < previous.cumulativeTotal || checkpoint_.cumulativeTotal < $.bscTotalCredited)
        {
            revert Points_BscTotalExceeded();
        }
        $.bscCheckpoints[BSC_CHAIN_ID] = checkpoint_;
        emit BscPointsCheckpointApproved(
            checkpoint_.token,
            checkpoint_.blockNumber,
            checkpoint_.root,
            checkpoint_.evidenceHash,
            checkpoint_.cumulativeTotal
        );
    }

    /// @notice Credits an approved proof for any wallet. No tokens, signatures or financial approvals are involved.
    /// @dev Roots are cumulative; replacing a root never resets the wallet's credited amount. The leaf binds this
    ///      proxy and destination chain as well as BSC, token, source block/hash/time, wallet and cumulative points.
    function creditBscPoints(address wallet, uint256 cumulativePoints, bytes32[] calldata proof) external {
        if (wallet == address(0)) revert Points_ZeroAddress();
        PointsStorage storage $ = _storage();
        BscPointsCheckpoint storage checkpoint_ = $.bscCheckpoints[BSC_CHAIN_ID];
        bytes32 leaf = _bscPointsLeaf(checkpoint_, wallet, cumulativePoints);
        if (checkpoint_.root == bytes32(0) || !MerkleProof.verifyCalldata(proof, checkpoint_.root, leaf)) {
            revert Points_BadBscProof();
        }
        uint256 previous = $.bscCredited[wallet];
        if (cumulativePoints <= previous) revert Points_NoNewBscPoints();
        uint256 delta = cumulativePoints - previous;
        uint256 nextTotal = $.bscTotalCredited + delta;
        if (nextTotal > checkpoint_.cumulativeTotal) revert Points_BscTotalExceeded();
        $.bscCredited[wallet] = cumulativePoints;
        $.bscTotalCredited = nextTotal;
        emit BscPointsCredited(wallet, checkpoint_.blockNumber, delta, cumulativePoints);
    }

    /// @dev Two static ABI blocks concatenate to exactly the original ten-word leaf encoding.
    ///      Keeping the encoding in this frame also permits unoptimized coverage compilation.
    function _bscPointsLeaf(BscPointsCheckpoint storage checkpoint_, address wallet, uint256 cumulativePoints)
        private
        view
        returns (bytes32)
    {
        bytes memory prefix = abi.encode(BSC_POINTS_DOMAIN, block.chainid, address(this), BSC_CHAIN_ID);
        bytes memory suffix = abi.encode(
            checkpoint_.token,
            checkpoint_.blockNumber,
            checkpoint_.blockHash,
            checkpoint_.timestamp,
            wallet,
            cumulativePoints
        );
        return keccak256(bytes.concat(keccak256(bytes.concat(prefix, suffix))));
    }

    /// @notice Removes mistaken token-stream points from an explicitly exempt protocol custodian.
    /// @dev Exemption alone does not erase cached balances or earlier accrual. This explicit governance act retires
    ///      both token streams and adjusts their totals without moving tokens or touching any curator position.
    ///      Later un-exemption cannot resurrect the retired points or the custodian's old maturity.
    function retireProtocolCustodyPoints(address custody) external onlyRole(Roles.UPGRADER_ROLE) {
        if (custody == address(0)) revert Points_ZeroAddress();
        PointsStorage storage $ = _storage();
        if (!_excluded($, custody)) revert Points_CustodyNotExempt(custody);
        Position storage s = $.sPos[custody];
        Position storage u = $.uPos[custody];
        uint256 shares = s.balance;
        uint256 usdfr = u.balance;
        uint256 sharePoints = s.accrued + _pending($, s, SHARE_UNIT, KIND_SHARES);
        uint256 usdfrPoints = u.accrued + _pending($, u, USDFR_UNIT, KIND_USDFR);
        $.totalTrackedShares -= shares;
        $.totalTrackedUsdfr -= usdfr;
        delete $.sPos[custody];
        delete $.uPos[custody];
        emit ProtocolCustodyPointsRetired(custody, sharePoints, usdfrPoints, shares, usdfr);
    }

    /// @notice The latest approved evidence-bound BSC checkpoint.
    function bscPointsCheckpoint() external view returns (BscPointsCheckpoint memory) {
        return _storage().bscCheckpoints[BSC_CHAIN_ID];
    }

    /// @notice Cumulative BSC share points already credited to this wallet.
    function bscPointsCredited(address wallet) external view returns (uint256) {
        return _storage().bscCredited[wallet];
    }

    /// @notice Approved cumulative BSC points and the portion already credited across all wallets.
    function bscPointsCreditTotals() external view returns (uint256 approved, uint256 credited) {
        PointsStorage storage $ = _storage();
        return ($.bscCheckpoints[BSC_CHAIN_ID].cumulativeTotal, $.bscTotalCredited);
    }

    // ── views ────────────────────────────────────────────────────────────

    /// @notice Total points of `wallet` across all three position types.
    function pointsOfWallet(address wallet) public view returns (uint256 total) {
        PointsStorage storage $ = _storage();
        Position storage s = $.sPos[wallet];
        Position storage u = $.uPos[wallet];
        total = s.accrued + _pending($, s, SHARE_UNIT, KIND_SHARES) + $.bscCredited[wallet] + u.accrued
            + _pending($, u, USDFR_UNIT, KIND_USDFR);
        for (uint256 c = 1; c <= Config.NUM_CLASSES; ++c) {
            Position storage cp = $.cPos[wallet][c];
            total += cp.accrued + _pending($, cp, USDFR_UNIT, KIND_CURATOR);
        }
    }

    /// @notice Point subtotals by source (dashboard split).
    function pointsBreakdown(address wallet)
        external
        view
        returns (uint256 fromShares, uint256 fromUSDfr, uint256 fromCurator)
    {
        PointsStorage storage $ = _storage();
        Position storage s = $.sPos[wallet];
        Position storage u = $.uPos[wallet];
        fromShares = s.accrued + _pending($, s, SHARE_UNIT, KIND_SHARES) + $.bscCredited[wallet];
        fromUSDfr = u.accrued + _pending($, u, USDFR_UNIT, KIND_USDFR);
        for (uint256 c = 1; c <= Config.NUM_CLASSES; ++c) {
            Position storage cp = $.cPos[wallet][c];
            fromCurator += cp.accrued + _pending($, cp, USDFR_UNIT, KIND_CURATOR);
        }
    }

    function trackedBalances(address wallet) external view returns (uint256 shares, uint256 usdfr) {
        PointsStorage storage $ = _storage();
        return ($.sPos[wallet].balance, $.uPos[wallet].balance);
    }

    function curatorTracked(address wallet, uint256 classId) external view returns (uint256) {
        return _storage().cPos[wallet][classId].balance;
    }

    function totals() external view returns (uint256 shares, uint256 usdfr, uint256 curator) {
        PointsStorage storage $ = _storage();
        return ($.totalTrackedShares, $.totalTrackedUsdfr, $.totalTrackedCurator);
    }

    function ratePerUnitDay() external view returns (uint256) {
        return _current().ratePerUnitDay;
    }

    function usdfrMultiplierBps() external view returns (uint32) {
        return _current().usdfrMultBps;
    }

    function curatorMultiplierBps() external view returns (uint32) {
        return _current().curatorMultBps;
    }

    function rateEpochCount() external view returns (uint256) {
        return _storage().rateEpochs.length;
    }

    function curatorModule() external view returns (address) {
        return _storage().curatorModule;
    }

    /// @notice Number of loss events recorded for `classId` (the class's loss-epoch count).
    /// @param classId The collateral class.
    /// @return The length of the class's append-only loss log.
    function curatorLossEpochCount(uint256 classId) external view returns (uint256) {
        return _storage().curatorLossTimes[classId].length;
    }

    /// @notice The instant of loss `lossEpoch` in `classId` (reverts if out of range).
    /// @param classId The collateral class.
    /// @param lossEpoch Zero-based index into the class's loss log.
    /// @return The block timestamp at which that loss was recorded.
    function curatorLossAt(uint256 classId, uint256 lossEpoch) external view returns (uint64) {
        return _storage().curatorLossTimes[classId][lossEpoch];
    }

    /// @notice The last recorded loss instant for `classId` (0 if none) — observability only.
    /// @param classId The collateral class.
    /// @return The timestamp of the most recent loss.
    function lastCuratorLossAt(uint256 classId) external view returns (uint64) {
        return _storage().lastCuratorLossAt[classId];
    }

    /// @notice Whether `wallet`'s first-loss position in `classId` is frozen by an
    ///         un-reconciled loss, and the instant its accrual is pinned at.
    /// @param wallet The curator.
    /// @param classId The collateral class.
    /// @return frozen True while the position has not been reconciled through every class loss.
    ///         A wallet that has never held first-loss in the class is never reported frozen,
    ///         however many losses the class has taken — it has nothing stale to freeze.
    /// @return frozenAt The accrual ceiling (the first un-reconciled loss instant); 0 if not frozen.
    function curatorFreezeStatus(address wallet, uint256 classId)
        external
        view
        returns (bool frozen, uint64 frozenAt)
    {
        PointsStorage storage $ = _storage();
        Position storage p = $.cPos[wallet][classId];
        if (!_isRealCuratorPosition(p)) return (false, 0);
        uint256 seen = p.seenLossEpoch;
        uint64[] storage times = $.curatorLossTimes[classId];
        if (seen >= times.length) return (false, 0);
        return (true, times[seen]);
    }

    /// @notice Points earned by `wallet`'s first-loss position in ONE class (accrued + pending).
    ///         Zero while the position is frozen beyond the loss instant.
    /// @param wallet The curator.
    /// @param classId The collateral class.
    /// @return The class's contribution to the wallet's curator points.
    function curatorPointsInClass(address wallet, uint256 classId) external view returns (uint256) {
        PointsStorage storage $ = _storage();
        Position storage p = $.cPos[wallet][classId];
        return p.accrued + _pending($, p, USDFR_UNIT, KIND_CURATOR);
    }

    /// @notice The class's dilution state: the loss round and the cumulative survival factor
    ///         (WAD) applied to cached curator balances within that round.
    /// @param classId The collateral class.
    /// @return lossRound Bumped on a pool wipe or on a loss recorded without a usable ratio.
    /// @return survivalWad Cumulative surviving fraction of the round, WAD-scaled.
    function curatorDilutionState(uint256 classId) external view returns (uint64 lossRound, uint256 survivalWad) {
        PointsStorage storage $ = _storage();
        return ($.curatorLossRound[classId], _survival($.curatorSurvivalWad[classId]));
    }

    // ── internals ──────────────────────────────────────────────────────────

    function _excluded(PointsStorage storage $, address wallet) private view returns (bool) {
        return $.compliance.isProtocolExempt(wallet);
    }

    function _multForKind(RateEpoch storage e, uint8 kind) private view returns (uint256) {
        if (kind == KIND_USDFR) return e.usdfrMultBps;
        if (kind == KIND_CURATOR) return e.curatorMultBps;
        return BPS; // shares: 1×
    }

    function _current() private view returns (RateEpoch storage) {
        RateEpoch[] storage epochs = _storage().rateEpochs;
        return epochs[epochs.length - 1];
    }

    function _appendEpoch(uint256 rate, uint32 usdfrMult, uint32 curatorMult) private {
        PointsStorage storage $ = _storage();
        $.rateEpochs.push(
            RateEpoch({
                start: uint64(block.timestamp),
                usdfrMultBps: usdfrMult,
                curatorMultBps: curatorMult,
                ratePerUnitDay: rate
            })
        );
        emit RateEpochAppended($.rateEpochs.length - 1, rate, usdfrMult, curatorMult);
    }

    function _track(PointsStorage storage $, Position storage p, uint256 amount, uint256 unit, uint8 kind, address w)
        private
    {
        _accrue($, p, unit, kind, w);
        uint256 bal = p.balance;
        uint64 nowTs = uint64(block.timestamp);
        if (bal == 0) {
            p.maturityStart = nowTs;
        } else {
            // Only age that affects the capped multiplier carries into newly added capital.
            // _accrue has already preserved all points earned before this balance change.
            uint256 retainedStart = p.maturityStart;
            if (nowTs > MATURITY_RAMP && retainedStart < nowTs - MATURITY_RAMP) {
                retainedStart = nowTs - MATURITY_RAMP;
            }
            p.maturityStart = uint64((bal * retainedStart + amount * nowTs) / (bal + amount));
        }
        p.balance = bal + amount;
    }

    function _untrack(PointsStorage storage $, Position storage p, uint256 amount, uint256 unit, uint8 kind, address w)
        private
        returns (uint256 dec)
    {
        _accrue($, p, unit, kind, w);
        uint256 bal = p.balance;
        dec = amount < bal ? amount : bal; // clamp so a re-hooked module can't underflow
        p.balance = bal - dec;
    }

    /// @dev Sets a position's balance to `target`, updating the matching total (P-02/P-04).
    ///      `totalKind` selects which total to adjust: 0 shares, 1 usdfr, 2 curator.
    function _reconcile(
        PointsStorage storage $,
        Position storage p,
        uint256 target,
        uint256 unit,
        uint8 kind,
        address w,
        uint8 totalKind
    ) private {
        uint256 bal = p.balance;
        if (target == bal) {
            _accrue($, p, unit, kind, w); // still checkpoint (locks the current epoch)
            return;
        }
        if (target > bal) {
            _track($, p, target - bal, unit, kind, w);
            if (totalKind == 0) $.totalTrackedShares += target - bal;
            else if (totalKind == 1) $.totalTrackedUsdfr += target - bal;
            else $.totalTrackedCurator += target - bal;
        } else {
            uint256 dec = _untrack($, p, bal - target, unit, kind, w);
            if (totalKind == 0) $.totalTrackedShares -= dec;
            else if (totalKind == 1) $.totalTrackedUsdfr -= dec;
            else $.totalTrackedCurator -= dec;
        }
    }

    function _accrue(PointsStorage storage $, Position storage p, uint256 unit, uint8 kind, address w) private {
        uint256 pending = _pending($, p, unit, kind);
        // The checkpoint always advances, INCLUDING for a frozen curator position. The freeze is
        // enforced entirely by the state predicate in `_accrualUpper` (`seenLossEpoch <` the
        // class loss count), which does not compare against `lastAccrual` — so advancing here
        // cannot lift it, while pinning `lastEpochIdx` at the loss (as an earlier revision of
        // this fix did) would have made `_pending` an unbounded rate-epoch traversal for every
        // frozen position, on every read AND on `reconcile` — the escape hatch itself.
        p.lastAccrual = uint64(block.timestamp);
        p.lastEpochIdx = uint32($.rateEpochs.length - 1);
        if (pending != 0) {
            p.accrued += pending;
            emit PointsAccrued(w, kind, pending);
        }
    }

    /// @dev Accrual integrated over the rate epochs since the position's last checkpoint —
    ///      each epoch contributes `B × (F(b−S) − F(a−S)) × rate_epoch / (1 day × unit)`,
    ///      so a rate change never reprices already-elapsed time (P-03). The epoch loop is
    ///      bounded by the number of (governance-rare, timelocked) rate changes since the
    ///      last checkpoint; a wallet's own transfers checkpoint it continuously.
    function _pending(PointsStorage storage $, Position storage p, uint256 unit, uint8 kind)
        private
        view
        returns (uint256 total)
    {
        if (p.balance == 0 || p.lastAccrual == 0 || block.timestamp <= p.lastAccrual) return 0;
        // AUDIT FIX: a curator position stops accruing at a class loss until reconciled (its
        // cached balance is stale-high after `absorbLoss`, which fires no per-curator hook).
        uint256 upper = _accrualUpper($, p);
        RateEpoch[] storage epochs = $.rateEpochs;
        for (uint256 i = p.lastEpochIdx; i < epochs.length; ++i) {
            uint256 a = epochs[i].start > p.lastAccrual ? epochs[i].start : p.lastAccrual;
            uint256 b = (i + 1 < epochs.length) ? epochs[i + 1].start : upper;
            if (b > upper) b = upper;
            if (b > a) total += _epochPoints(p.balance, p.maturityStart, a, b, unit, epochs[i], kind);
        }
    }

    /// @dev The upper time bound for accrual: now, unless the position is a curator position
    ///      frozen by an un-reconciled class loss, in which case it is the instant of the FIRST
    ///      loss the position has not been reconciled through (H-03). Anchoring on the first
    ///      unseen loss — not on a single overwritable "latest loss" timestamp — is what stops
    ///      a later same-class loss from re-opening an earlier freeze window.
    function _accrualUpper(PointsStorage storage $, Position storage p) private view returns (uint256 upper) {
        upper = block.timestamp;
        uint32 cid = p.classId;
        if (cid == 0) return upper;
        uint64[] storage times = $.curatorLossTimes[cid];
        uint256 seen = p.seenLossEpoch;
        if (seen >= times.length) return upper; // reconciled through every recorded loss
        uint64 frozenAt = times[seen];
        if (frozenAt < upper) upper = frozenAt;
    }

    /// @dev Appends a loss epoch for `classId` and folds its dilution ratio into the class's
    ///      cumulative survival factor. `before == 0 || after == 0 || after > before` means the
    ///      ratio is unusable (a wipe, or a legacy/migrated loss that carried no ratio): the
    ///      loss ROUND is bumped instead, which distrusts every cached balance in the class.
    function _recordCuratorLoss(PointsStorage storage $, uint256 classId, uint256 balBefore, uint256 balAfter)
        private
    {
        uint64 at = uint64(block.timestamp);
        $.lastCuratorLossAt[classId] = at; // legacy field, retained for observability + migration
        uint64[] storage times = $.curatorLossTimes[classId];
        times.push(at);
        if (balBefore == 0 || balAfter == 0 || balAfter > balBefore) {
            $.curatorLossRound[classId] += 1;
            $.curatorSurvivalWad[classId] = WAD;
        } else {
            uint256 next = _survival($.curatorSurvivalWad[classId]) * balAfter / balBefore;
            if (next == 0) {
                // Precision exhausted by successive dilutions: distrust rather than under-state.
                $.curatorLossRound[classId] += 1;
                $.curatorSurvivalWad[classId] = WAD;
            } else {
                $.curatorSurvivalWad[classId] = next;
            }
        }
        emit CuratorLossRecorded(classId, times.length - 1, at, balBefore, balAfter);
    }

    /// @dev 0 encodes "unset" for both the class factor and a position's snapshot of it, so a
    ///      never-written slot (including on an upgraded proxy) reads as "no dilution".
    function _survival(uint256 v) private pure returns (uint256) {
        return v == 0 ? WAD : v;
    }

    /// @dev A position that has never held first-loss in the class (no balance, no accrual, no
    ///      maturity anchor). Such a position is never "frozen": there is nothing stale in it,
    ///      and thawing it would write storage and emit events for every wallet reconciled.
    function _isRealCuratorPosition(Position storage p) private view returns (bool) {
        return p.balance != 0 || p.accrued != 0 || p.maturityStart != 0;
    }

    /// @dev Writes `p`'s cached first-loss balance down by every class loss it has not yet
    ///      absorbed (H-03, BALANCE/MATURITY axis). `absorbLoss` dilutes every curator in the
    ///      class EXACTLY pro-rata, so the ratio is enough — no per-curator hook is needed.
    ///      Accrual up to the freeze ceiling is credited at the pre-loss balance FIRST, then the
    ///      balance drops; `maturityStart` is untouched, which is correct — the SURVIVING
    ///      capital has genuinely been posted since then, and any later top-up is blended
    ///      against it by `_track`. Monotone: the balance can only move down here.
    function _applyCuratorDilution(PointsStorage storage $, Position storage p, uint256 classId, address wallet)
        private
    {
        uint64 round = $.curatorLossRound[classId];
        uint256 cur = _survival($.curatorSurvivalWad[classId]);
        uint256 seen = _survival(p.seenSurvivalWad);
        if (p.seenLossRound == round && seen == cur) return; // nothing new to absorb
        uint256 bal = p.balance;
        if (bal != 0) {
            _accrue($, p, USDFR_UNIT, KIND_CURATOR, wallet);
            // A round change means a wipe or an unusable ratio: nothing cached is trustworthy.
            uint256 newBal = p.seenLossRound != round ? 0 : bal * cur / seen;
            if (newBal > bal) newBal = bal; // defensive: the factor never grows within a round
            if (newBal != bal) {
                p.balance = newBal;
                $.totalTrackedCurator -= bal - newBal;
                emit CuratorBalanceDiluted(wallet, classId, bal, newBal);
            }
        }
        p.seenLossRound = round;
        p.seenSurvivalWad = cur;
    }

    /// @dev Marks `p` reconciled through every recorded loss of `classId`, emitting the thaw.
    ///      Returns true when the watermark actually moved (i.e. the position WAS frozen).
    function _syncLossWatermark(PointsStorage storage $, Position storage p, uint256 classId, address wallet)
        private
        returns (bool)
    {
        uint256 count = $.curatorLossTimes[classId].length;
        if (p.seenLossEpoch >= count) return false; // not frozen — nothing to clear
        p.seenLossEpoch = uint64(count);
        emit CuratorPositionThawed(wallet, classId, uint64(count));
        return true;
    }

    /// @dev Clears a curator position's freeze from `reconcile()`, i.e. only after the balance
    ///      has been snapped to the live `postedOf`. Positions that never held first-loss in the
    ///      class are skipped, so reconciling an arbitrary wallet writes nothing and emits
    ///      nothing for the classes it never participated in.
    function _thawCurator(PointsStorage storage $, Position storage p, uint256 classId, address wallet) private {
        if (!_isRealCuratorPosition(p)) return;
        if (!_syncLossWatermark($, p, classId, wallet)) return;
        p.lastAccrual = uint64(block.timestamp);
        p.lastEpochIdx = uint32($.rateEpochs.length - 1);
    }

    /// @dev One rate epoch's contribution — in its own frame to keep `_pending` off the
    ///      stack-too-deep cliff without via-ir.
    function _epochPoints(
        uint256 bal,
        uint256 start,
        uint256 a,
        uint256 b,
        uint256 unit,
        RateEpoch storage e,
        uint8 kind
    ) private view returns (uint256) {
        uint256 dF = _rampIntegral(b >= start ? b - start : 0) - _rampIntegral(a >= start ? a - start : 0);
        uint256 rate = e.ratePerUnitDay * _multForKind(e, kind) / BPS;
        return bal * dF / WAD * rate / (1 days * unit);
    }

    /// @dev F(x) = ∫₀ˣ m(τ)dτ, m(τ) = 1 + min(τ, RAMP)/RAMP, WAD-scaled.
    function _rampIntegral(uint256 x) internal pure returns (uint256) {
        if (x <= MATURITY_RAMP) {
            return x * WAD + (x * x * WAD) / (2 * MATURITY_RAMP);
        }
        return (3 * MATURITY_RAMP * WAD) / 2 + 2 * (x - MATURITY_RAMP) * WAD;
    }

    function _authorizeUpgrade(address) internal override onlyRole(Roles.UPGRADER_ROLE) {}

    function _storage() private pure returns (PointsStorage storage $) {
        assembly {
            $.slot := POINTS_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/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/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/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/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/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/cryptography/Hashes.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/Hashes.sol)

pragma solidity ^0.8.20;

/**
 * @dev Library of standard hash functions.
 *
 * _Available since v5.1._
 */
library Hashes {
    /**
     * @dev Commutative Keccak256 hash of a sorted pair of bytes32. Frequently used when working with merkle proofs.
     *
     * NOTE: Equivalent to the `standardNodeHash` in our https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
     */
    function commutativeKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32) {
        return a < b ? efficientKeccak256(a, b) : efficientKeccak256(b, a);
    }

    /**
     * @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
     */
    function efficientKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32 value) {
        assembly ("memory-safe") {
            mstore(0x00, a)
            mstore(0x20, b)
            value := keccak256(0x00, 0x40)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/MerkleProof.sol)
// This file was procedurally generated from scripts/generate/templates/MerkleProof.js.

pragma solidity ^0.8.20;

import {Hashes} from "./Hashes.sol";

/**
 * @dev These functions deal with verification of Merkle Tree proofs.
 *
 * The tree and the proofs can be generated using our
 * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
 * You will find a quickstart guide in the readme.
 *
 * WARNING: You should avoid using leaf values that are 64 bytes long prior to
 * hashing, or use a hash function other than keccak256 for hashing leaves.
 * This is because the concatenation of a sorted pair of internal nodes in
 * the Merkle tree could be reinterpreted as a leaf value.
 * OpenZeppelin's JavaScript library generates Merkle trees that are safe
 * against this attack out of the box.
 *
 * IMPORTANT: Consider memory side-effects when using custom hashing functions
 * that access memory in an unsafe way.
 *
 * NOTE: This library supports proof verification for merkle trees built using
 * custom _commutative_ hashing functions (i.e. `H(a, b) == H(b, a)`). Proving
 * leaf inclusion in trees built using non-commutative hashing functions requires
 * additional logic that is not supported by this library.
 */
library MerkleProof {
    /**
     *@dev The multiproof provided is not valid.
     */
    error MerkleProofInvalidMultiproof();

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with the default hashing function.
     */
    function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with the default hashing function.
     */
    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with a custom hashing function.
     */
    function verify(
        bytes32[] memory proof,
        bytes32 root,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processProof(proof, leaf, hasher) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with a custom hashing function.
     */
    function processProof(
        bytes32[] memory proof,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = hasher(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with the default hashing function.
     */
    function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProofCalldata(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with the default hashing function.
     */
    function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with a custom hashing function.
     */
    function verifyCalldata(
        bytes32[] calldata proof,
        bytes32 root,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processProofCalldata(proof, leaf, hasher) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with a custom hashing function.
     */
    function processProofCalldata(
        bytes32[] calldata proof,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = hasher(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in memory with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProof}.
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProof(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in memory with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = Hashes.commutativeKeccak256(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in memory with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProof}.
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processMultiProof(proof, proofFlags, leaves, hasher) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in memory with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = hasher(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in calldata with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProofCalldata}.
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in calldata with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = Hashes.commutativeKeccak256(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in calldata with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProofCalldata}.
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves, hasher) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in calldata with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = hasher(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

src/ComplianceRegistry.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 {IComplianceRegistry} from "./interfaces/IComplianceRegistry.sol";
import {Roles} from "./libraries/Roles.sol";

/// @title ComplianceRegistry
/// @notice Compliance capability layer (ADR-0011, amended by the 2026-07-14 Forest Road
///         directive): a KYC allowlist consulted ONLY at the mint/redeem primary gate, and a
///         narrow SANCTIONS blocklist consulted on transfers. Transfers are otherwise
///         permissionless — the per-token transfer-allowlist capability was removed. Capability
///         lives here; eligibility/sanctions POLICY is governance/counsel's, expressed purely
///         as list contents. This is a regulatory-posture decision owned by Forest Road +
///         counsel (STATE.md); nothing here characterizes any instrument (brief Part 0.5).
/// @dev Trust note: list administration is role-gated (COMPLIANCE_ADMIN_ROLE for accounts,
///      DEFAULT_ADMIN_ROLE i.e. timelocked governance for per-token restriction flags).
///      Nothing in this contract asserts anything about the securities characterization
///      of any protocol instrument (brief Part 0.5).
contract ComplianceRegistry is Initializable, AccessControlUpgradeable, UUPSUpgradeable, IComplianceRegistry {
    /// @custom:storage-location erc7201:forestroad.storage.ComplianceRegistry
    /// @dev Fields are append-only (ERC-7201 namespaced struct) for upgrade safety.
    struct ComplianceStorage {
        mapping(address account => bool) allowed;
        mapping(address account => bool) blocked;
        // Protocol module addresses (vault, queue, reserves, curator, sGrove,
        // defaultManager, waterfall, controller, feeRecipient). A module is never treated as
        // a sanctioned party in canTransfer — else a COMPLIANCE_ADMIN block of a module
        // address would brick the "never-pausable" cascade/redemption. Sanctions still apply
        // to the NON-module counterparty (R2-H-01 fix). DEFAULT_ADMIN-managed (timelock),
        // toggle-able so a deprecated module can be de-listed on an upgrade.
        mapping(address module => bool) protocolExempt;
        // Borrower principal may leave ReserveManager only for a destination explicitly
        // approved by timelocked governance. This is separate from the operational KYC list:
        // KYC permits primary USDfr use; it never authorizes a treasury payout.
        mapping(address account => bool) fundingRecipientApproved;
    }

    // keccak256(abi.encode(uint256(keccak256("forestroad.storage.ComplianceRegistry")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant COMPLIANCE_STORAGE_LOCATION =
        0x03801aefafc5a4dd742851861c13346935b02c9e4c08bfcf4aed3079668d5300;

    error ComplianceRegistry_ZeroAddress();
    error ComplianceRegistry_LengthMismatch();

    /// @notice Emitted when a protocol module's compliance exemption changes.
    event ProtocolExemptUpdated(address indexed module, bool exempt);

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    /// @notice Initializes roles. `admin` is the governance timelock (DEFAULT_ADMIN_ROLE).
    /// @param admin Governance admin (timelock).
    /// @param complianceAdmin Operational list manager (may equal admin initially).
    /// @param upgrader Upgrade authority (the timelock).
    /// @param initialProtocolExempt The initial fee recipient or protocol module that must
    ///        be unbrickable before dependent contracts are initialized.
    function initialize(address admin, address complianceAdmin, address upgrader, address initialProtocolExempt)
        external
        initializer
    {
        if (
            admin == address(0) || complianceAdmin == address(0) || upgrader == address(0)
                || initialProtocolExempt == address(0)
        ) {
            revert ComplianceRegistry_ZeroAddress();
        }
        __AccessControl_init();
        __UUPSUpgradeable_init();
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        _grantRole(Roles.COMPLIANCE_ADMIN_ROLE, complianceAdmin);
        _grantRole(Roles.UPGRADER_ROLE, upgrader);
        _storage().protocolExempt[initialProtocolExempt] = true;
        emit ProtocolExemptUpdated(initialProtocolExempt, true);
    }

    // ── List administration ──────────────────────────────────────────────

    /// @notice Sets KYC allowlist status for `account`.
    function setAllowed(address account, bool allowed_) external onlyRole(Roles.COMPLIANCE_ADMIN_ROLE) {
        if (account == address(0)) revert ComplianceRegistry_ZeroAddress();
        _storage().allowed[account] = allowed_;
        emit AllowlistUpdated(account, allowed_);
    }

    /// @notice Batch allowlist update (broad-access onboarding, ADR-0011).
    function setAllowedBatch(address[] calldata accounts, bool allowed_)
        external
        onlyRole(Roles.COMPLIANCE_ADMIN_ROLE)
    {
        uint256 len = accounts.length;
        for (uint256 i = 0; i < len; ++i) {
            if (accounts[i] == address(0)) revert ComplianceRegistry_ZeroAddress();
            _storage().allowed[accounts[i]] = allowed_;
            emit AllowlistUpdated(accounts[i], allowed_);
        }
    }

    /// @notice Sets jurisdiction-block status for `account`. Blocked accounts fail every
    ///         compliance check regardless of allowlist status.
    function setJurisdictionBlocked(address account, bool blocked_) external onlyRole(Roles.COMPLIANCE_ADMIN_ROLE) {
        if (account == address(0)) revert ComplianceRegistry_ZeroAddress();
        _storage().blocked[account] = blocked_;
        emit JurisdictionBlockUpdated(account, blocked_);
    }

    /// @notice Approves or removes a borrower-principal destination.
    /// @dev Timelocked governance only. The operational compliance administrator can stop a
    ///      payout by blocking an address, but cannot add a destination to this list.
    function setFundingRecipientAllowed(address account, bool approved) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (account == address(0)) revert ComplianceRegistry_ZeroAddress();
        _storage().fundingRecipientApproved[account] = approved;
        emit FundingRecipientApprovalUpdated(account, approved);
    }

    /// @notice Marks `module` as a protocol-exempt address whose transfers are never
    ///         blockable by list state (see the storage note). Timelocked governance
    ///         only — set once for every internal-value-moving protocol contract at
    ///         deploy so the compliance capability can never brick the cascade/queue.
    function setProtocolExempt(address module, bool exempt) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (module == address(0)) revert ComplianceRegistry_ZeroAddress();
        _storage().protocolExempt[module] = exempt;
        emit ProtocolExemptUpdated(module, exempt);
    }

    /// @notice True if `module` is exempt from all transfer blocking (a protocol module).
    function isProtocolExempt(address module) external view returns (bool) {
        return _storage().protocolExempt[module];
    }

    // ── Views (IComplianceRegistry) ──────────────────────────────────────

    /// @inheritdoc IComplianceRegistry
    function isAllowed(address account) public view returns (bool) {
        ComplianceStorage storage $ = _storage();
        return $.allowed[account] && !$.blocked[account];
    }

    /// @inheritdoc IComplianceRegistry
    function isJurisdictionBlocked(address account) external view returns (bool) {
        return _storage().blocked[account];
    }

    /// @inheritdoc IComplianceRegistry
    function isFundingRecipientAllowed(address account) external view returns (bool) {
        ComplianceStorage storage $ = _storage();
        return $.fundingRecipientApproved[account] && !$.blocked[account];
    }

    /// @inheritdoc IComplianceRegistry
    /// @dev DIRECTIVE 2026-07-14 (Forest Road): protocol tokens are NEVER KYC/allowlist-gated
    ///      on transfer — transfers are permissionless. The only on-chain transfer restriction
    ///      is a narrow SANCTIONS freeze (the `blocked` list). KYC is enforced solely at the
    ///      mint/redeem primary gate (`MintRedeemController`). This supersedes the ADR-0011
    ///      transfer-restriction capability (removed); a regulatory-posture change owned by
    ///      Forest Road + counsel (recorded in STATE.md). The `token` argument is retained for
    ///      interface stability but no longer affects the result.
    function canTransfer(address, address from, address to) external view returns (bool) {
        ComplianceStorage storage $ = _storage();
        // Burns (loss cascade, redemption settlement) are never blockable.
        if (to == address(0)) return true;
        // Sanctions freeze — the ONLY transfer restriction. A sanctioned party is denied even
        // when the counterparty is an exempt protocol module (AUDIT FIX R2-H-01: a blocked
        // wallet can no longer route value out through the exempt vault, because the sanctions
        // check now precedes the exemption). Protocol modules are never themselves treated as
        // "blocked", so a list error can't brick the never-pausable cascade.
        if ($.blocked[from] && !$.protocolExempt[from]) return false;
        if ($.blocked[to] && !$.protocolExempt[to]) return false;
        // Otherwise permissionless.
        return true;
    }

    // ── UUPS ─────────────────────────────────────────────────────────────

    function _authorizeUpgrade(address) internal override onlyRole(Roles.UPGRADER_ROLE) {}

    function _storage() private pure returns (ComplianceStorage storage $) {
        assembly {
            $.slot := COMPLIANCE_STORAGE_LOCATION
        }
    }
}

src/interfaces/IComplianceRegistry.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;

/// @title IComplianceRegistry
/// @notice Compliance capability layer (ADR-0011, as amended by the 2026-07-14 directive):
///         a KYC allowlist consulted ONLY at the mint/redeem primary gate, and a narrow
///         sanctions blocklist consulted on transfers. The per-token transfer-allowlist
///         capability was removed — transfers are permissionless (sanctions-only). Policy
///         (who is eligible/sanctioned) is set by governance/counsel off this interface.
interface IComplianceRegistry {
    /// @notice Emitted when an account's KYC allowlist status changes.
    event AllowlistUpdated(address indexed account, bool allowed);
    /// @notice Emitted when an account's sanctions/jurisdiction-block status changes.
    event JurisdictionBlockUpdated(address indexed account, bool blocked);
    /// @notice Timelocked governance changed an address's borrower-payout approval.
    /// @dev This list is deliberately independent of the operational KYC allowlist.
    event FundingRecipientApprovalUpdated(address indexed account, bool approved);

    /// @notice True if `account` has passed KYC and may use the gated primary paths
    ///         (USDfr mint/redeem). Holding and transferring are permissionless.
    function isAllowed(address account) external view returns (bool);

    /// @notice True if `account` is on the sanctions/jurisdiction blocklist.
    function isJurisdictionBlocked(address account) external view returns (bool);

    /// @notice True only when timelocked governance approved `account` as a borrower-payout
    ///         destination and the account is not currently jurisdiction-blocked.
    function isFundingRecipientAllowed(address account) external view returns (bool);

    /// @notice True for a governance-designated internal protocol module.
    function isProtocolExempt(address module) external view returns (bool);

    /// @notice Transfer gate consulted by protocol tokens on every transfer. Transfers are
    ///         permissionless except for sanctioned (blocked) parties; burns are always
    ///         permitted; protocol modules are never treated as blocked.
    /// @param token Retained for interface stability; no longer affects the result.
    /// @param from Sender (zero on mint).
    /// @param to Recipient (zero on burn).
    /// @return True if the transfer may proceed.
    function canTransfer(address token, address from, address to) external view returns (bool);
}

src/interfaces/ICuratorModule.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;

/// @title ICuratorModule — per-class curator first-loss vaults (ADR-0004)
/// @notice Curators (anchor: Forest Road, $10M/class default; additional curators
///         pluggable per class) post USDfr first-loss capital that absorbs realized
///         losses BEFORE the sGROVE backstop and depositor principal (CLAUDE.md §1.3
///         cascade ordering). Multi-curator stakes in one class share losses exactly
///         pro-rata via internal shares. Withdrawals are constrained by subordination
///         headroom: posted capital protecting live exposure cannot leave.
interface ICuratorModule {
    // ── Events ───────────────────────────────────────────────────────────
    event CuratorApproved(uint256 indexed classId, address indexed curator, bool approved);
    event FirstLossTargetSet(uint256 indexed classId, uint256 target);
    // `round` disambiguates share attribution across a wipe-out (audit fix, §3.1).
    event FirstLossPosted(
        uint256 indexed classId, address indexed curator, uint256 amount, uint256 shares, uint256 round
    );
    event FirstLossWithdrawn(
        uint256 indexed classId, address indexed curator, uint256 amount, uint256 shares, uint256 round
    );
    /// @notice Emitted on every cascade layer-1 absorption (residual > 0 escalates).
    event LossAbsorbed(uint256 indexed classId, uint256 loss, uint256 absorbed, uint256 residual);
    /// @notice Emitted when a fully-wiped class pool restarts a new share round.
    event PoolRoundAdvanced(uint256 indexed classId, uint256 newRound);
    /// @notice Share units were divided by a power of two to retain representability.
    event PoolSharesNormalized(uint256 indexed classId, uint256 shift, uint256 totalShares);
    /// @notice AUDIT FIX (SWEEP-4 S4-R1). A round was CLOSED as economically wiped while a
    ///         residual balance still stood, so the residual's ownership was snapshotted for the
    ///         closing cohort instead of being forfeited to the pool.
    /// @param classId The class whose round closed.
    /// @param closedRound The round that closed.
    /// @param residual The USDfr still standing in the pool at the close.
    /// @param closedShares Shares of the closed round that share `residual` pro-rata.
    /// @param carriedShares Shares of the SUCCEEDING round the closed cohort collectively owns
    ///        (equal to `residual`, because the new round opens at a share price of exactly 1).
    event ClosedRoundSnapshotted(
        uint256 indexed classId,
        uint256 indexed closedRound,
        uint256 residual,
        uint256 closedShares,
        uint256 carriedShares
    );
    /// @notice AUDIT FIX (SWEEP-4 S4-R1). A curator's stale-round stake was walked forward through
    ///         one or more CLOSED rounds. `settledShares == 0` means the stale stake was genuinely
    ///         worth nothing and was cleared; `toRound` below the class's live round means the walk
    ///         hit `MAX_CLOSED_ROUND_HOPS` and `claimClosedRound` must be called again.
    /// @param classId The class whose stake was settled.
    /// @param curator The stake's owner (the settler may be anyone).
    /// @param fromRound The round the stake held before the walk.
    /// @param toRound The round the stake holds after it.
    /// @param staleShares Shares held at `fromRound`.
    /// @param settledShares Shares held at `toRound`.
    event ClosedRoundSettled(
        uint256 indexed classId,
        address indexed curator,
        uint256 indexed fromRound,
        uint256 toRound,
        uint256 staleShares,
        uint256 settledShares
    );
    /// @notice Emitted when a default entering a class freezes curator withdrawals.
    ///         `count` is the number of unresolved defaults now outstanding on the class.
    event ClassDefaultFrozen(uint256 indexed classId, uint256 count);
    /// @notice Emitted when governance lifts one default freeze from a class.
    event ClassDefaultFreezeLifted(uint256 indexed classId, uint256 count);
    /// @notice AUDIT FIX (R6-CF1). The ReserveManager whose custody-loss window gates withdrawals.
    event ReserveManagerUpdated(address indexed reserves);
    /// @notice AUDIT FIX (R6-CF1). The governor the pre-arm duration is derived from (0 = the
    ///         `Config` launch parameters are used as the floor and nothing overrides them).
    event GovernorUpdated(address indexed governor);
    /// @notice AUDIT FIX (R6-CF1). A guardian armed the custody freeze ahead of governance.
    /// @param guardian The arming guardian.
    /// @param expiry Unix time at which the pre-arm lapses on its own.
    /// @param count Consecutive pre-arms used out of the budget, after this one.
    event CustodyFreezePreArmed(address indexed guardian, uint64 expiry, uint32 count);
    /// @notice AUDIT FIX (R6-CF1). Governance declared a FALSE ALARM: the guardian pre-arm limb is
    ///         cleared and the budget replenished. This can NEVER release a genuine custody freeze
    ///         — the derived limbs in `IReserveManager.custodyLossUnabsorbed` stand on their own.
    event CustodyFreezePreArmCancelled(uint64 previousExpiry);
    /// @notice AUDIT FIX (F3-PA-a). Governance replenished the guardian's pre-arm budget while
    ///         LEAVING the standing pre-arm in force — "we looked, the incident is real, keep
    ///         going". `expiry` is echoed unchanged precisely so an observer can verify that the
    ///         protection survived the replenishment.
    /// @param spent Budget units returned to the guardian.
    /// @param expiry The standing pre-arm expiry, unchanged by this call.
    event CustodyFreezePreArmBudgetReplenished(uint32 spent, uint64 expiry);
    /// @notice AUDIT FIX (F3-PA-b). A previous pre-arm had lapsed and layer-1 capital had stood
    ///         unfrozen for the full `custodyPreArmCooldown()`, so the consecutive counter reset
    ///         and this arm opened a NEW episode.
    /// @param spent Budget the lapsed episode had used.
    /// @param lapsedExpiry Expiry of the episode that just ended.
    event CustodyFreezePreArmEpisodeReset(uint32 spent, uint64 lapsedExpiry);
    /// @notice AUDIT FIX (F3-PA-c). THE CAP BOUND. One pre-arm window no longer outlasts the live
    ///         governance path, so the freeze WILL lapse before governance can ratify it unless
    ///         `replenishCustodyPreArmBudget` carries it. Emitted at the arm so the condition can
    ///         never arise silently; `script/Validate.s.sol` refuses a deployment in this regime.
    /// @param livePath The unbounded `votingDelay + votingPeriod + minDelay` reading, in seconds.
    /// @param duration The window actually granted, bounded by `CUSTODY_PRE_ARM_MAX_PATH`.
    /// @param count Consecutive pre-arms used out of the budget, after this one.
    event CustodyFreezePreArmTruncated(uint256 livePath, uint64 duration, uint32 count);

    // ── Errors ───────────────────────────────────────────────────────────
    error Curator_ZeroAddress();
    error Curator_ZeroAmount();
    /// @notice The proposed points module has no code. Refused for the same reason
    ///         `USDfr.setPointsModule` refuses it (C4-USDFR-01): the points hooks return no
    ///         data, so solc emits an `extcodesize` guard that reverts OUTSIDE the fail-open
    ///         `try` — turning a hook that must never block the cascade into one that always
    ///         does. See P-48b.
    /// @param module The codeless address that was refused.
    error Curator_PointsModuleNotAContract(address module);
    error Curator_UnknownClass(uint256 classId);
    error Curator_NotApprovedCurator(uint256 classId, address curator);
    error Curator_InsufficientStake(uint256 classId, address curator, uint256 requested, uint256 posted);
    error Curator_HeadroomExceeded(uint256 classId, uint256 requested, uint256 headroom);
    /// @notice Withdrawals are frozen because the class has an unresolved default
    ///         (audit R4-EC2: stops a curator front-running realizeLoss to duck a loss).
    error Curator_ClassDefaultFrozen(uint256 classId);
    /// @notice liftDefaultFreeze called on a class with no outstanding default freeze.
    error Curator_NotFrozen(uint256 classId);
    /// @notice AUDIT FIX (R6-CF1). Withdrawals are frozen because a reserve-CUSTODY loss is
    ///         recognised, observable or incompletely absorbed, or because a guardian has
    ///         pre-armed the freeze. Curator capital is cascade LAYER 1 for that loss and may not
    ///         exit ahead of it — the custody twin of `Curator_ClassDefaultFrozen` (R4-EC2).
    error Curator_CustodyLossFrozen();
    /// @notice AUDIT FIX (R6-CF1). No ReserveManager is wired, so the custody-loss window cannot
    ///         be evaluated. Withdrawals fail CLOSED rather than proceeding blind.
    error Curator_ReserveNotWired();
    /// @notice AUDIT FIX (R6-CF1). The guardian's consecutive pre-arm budget is spent. Only
    ///         governance can replenish it, which is what bounds a unilateral guardian freeze.
    error Curator_PreArmBudgetExhausted(uint32 requested, uint32 max);
    /// @notice AUDIT FIX (R6-CF1). `cancelCustodyPreArm` with nothing armed and no budget used.
    error Curator_NoPreArm();
    /// @notice AUDIT FIX (R6-CF1). `setReserveManager` was given an address that is not a
    ///         ReserveManager. Wiring the freeze to the wrong contract would make the guard read
    ///         someone else's state, so this fails loudly rather than accepting it.
    error Curator_InvalidReserveManager(address reserves);
    /// @notice AUDIT FIX (R6-CF1). `setGovernor` was given an address with no code, which could
    ///         never supply a live governance path.
    error Curator_InvalidGovernor(address governor);
    error Curator_ReserveManagerChangeFrozen();
    error Curator_ReserveLossWithdrawalsFrozen();
    error Curator_ShareCapacityExceeded(uint256 amount, uint256 availableShares);
    /// @notice AUDIT FIX (SWEEP-4 S4-R1). The caller holds a stake in a round that closed more than
    ///         one round ago, so a single conversion cannot bring it to the live round. Call
    ///         `claimClosedRound` (permissionless) until `stakeRound == liveRound`, then retry.
    ///         Posting or withdrawing is REFUSED rather than silently erasing the residual claim.
    error Curator_UnsettledClosedRound(uint256 classId, uint256 stakeRound, uint256 liveRound);

    // ── Curator paths ────────────────────────────────────────────────────
    /// @notice Posts `amount` USDfr of first-loss capital to `classId`'s pool.
    ///         Caller must be an approved curator for the class.
    function postFirstLoss(uint256 classId, uint256 amount) external;

    /// @notice Withdraws `amount` USDfr of the caller's stake, capped by BOTH the
    ///         caller's pro-rata stake and the class's subordination headroom.
    function withdrawFirstLoss(uint256 classId, uint256 amount) external;

    /// @notice AUDIT FIX (SWEEP-4 S4-R1). Converts `curator`'s stake in a CLOSED round into its
    ///         pro-rata slice of the succeeding round's shares. PERMISSIONLESS — anyone may settle
    ///         anyone, because a curator who cannot settle cannot post or withdraw either, and
    ///         layer-1 liveness must not depend on one address being available.
    /// @dev Moves NO value: the shares it assigns were minted at the close and have been part of
    ///      `poolShares(classId)` ever since. It is a pure re-attribution of ownership, which is why
    ///      it is not pausable and not gated by either withdrawal freeze — neither of those governs
    ///      attribution, and both still bind on `withdrawFirstLoss`.
    ///      Idempotent: a stake already on the live round is a no-op. Call it repeatedly to walk a
    ///      stake through several consecutive closes.
    function claimClosedRound(uint256 classId, address curator) external;

    // ── Cascade (credit layer only) ──────────────────────────────────────
    /// @notice Absorbs up to `loss` from the class pool (cascade layer 1). Transfers
    ///         the absorbed USDfr to `msg.sender` (the DefaultManager), which burns it
    ///         in the same transaction against the principal write-down (ADR-0012).
    /// @return absorbed Amount taken from the pool (== min(loss, pool balance)).
    /// @return residual Loss remaining for the next cascade layer.
    function absorbLoss(uint256 classId, uint256 loss) external returns (uint256 absorbed, uint256 residual);

    /// @notice Absorbs a classless protocol loss across all five pools, weighted by balances
    ///         snapshotted before any pool is changed. Rounding dust is assigned deterministically
    ///         to the lowest-numbered non-empty pools with snapshot headroom.
    /// @dev Transfers the aggregate absorbed USDfr to the caller for same-transaction burning.
    function absorbGlobalLoss(uint256 loss) external returns (uint256 absorbed, uint256 residual);

    // ── Default freeze (audit R4-EC2) ────────────────────────────────────
    /// @notice Records that a facility in `classId` has entered default, freezing curator
    ///         withdrawals for the class until governance lifts it. Called by the
    ///         DefaultManager (CREDIT_ROLE) on declareDefault / liquidate. Increments an
    ///         unresolved-default counter so concurrent defaults each require a lift.
    function freezeOnDefault(uint256 classId) external;

    /// @notice Governance (timelock) lifts one default freeze from `classId` once a
    ///         workout resolves. Reverts if the class has no outstanding freeze.
    function liftDefaultFreeze(uint256 classId) external;

    /// @notice Number of unresolved defaults freezing withdrawals on a class (0 = open).
    function unresolvedDefaults(uint256 classId) external view returns (uint256);

    // ── Custody-loss freeze (audit R6-CF1) ───────────────────────────────

    /// @notice AUDIT FIX (R6-CF1). True while curator first-loss capital is frozen by a
    ///         reserve-CUSTODY loss (recognised, observable, or incompletely absorbed) or by a
    ///         live guardian pre-arm. Class-independent: a custody loss is allocated across ALL
    ///         five pools by `absorbGlobalLoss`, so the freeze is protocol-wide.
    /// @dev Reads as TRUE when no ReserveManager is wired. "Cannot tell" must never read as
    ///      "clear" on a guard whose whole job is to stop capital leaving ahead of a loss.
    function custodyFreezeActive() external view returns (bool);

    /// @notice AUDIT FIX (R6-CF1). Guardian arms the custody freeze ahead of governance, for
    ///         losses that are known but not yet visible on-chain (a custodian insolvency, a legal
    ///         seizure, an off-chain balance frozen). A guardian may ARM but has NO release.
    function preArmCustodyFreeze() external;

    /// @notice AUDIT FIX (R6-CF1). Governance declares a FALSE ALARM: clears the guardian pre-arm
    ///         limb and replenishes the pre-arm budget.
    /// @dev It CANNOT release a real custody freeze: the derived limbs are unaffected. That is why
    ///      giving governance this cancel does not hand it a loss-dodging lever.
    ///
    ///      AUDIT FIX (F3-PA-a). This is the FALSE-ALARM lever only. To keep a REAL incident frozen
    ///      while returning budget to the guardian, use `replenishCustodyPreArmBudget` — using this
    ///      one for that purpose destroys the protection it was called to extend.
    function cancelCustodyPreArm() external;

    /// @notice AUDIT FIX (F3-PA-a). Governance returns the guardian's pre-arm budget WITHOUT
    ///         touching the standing pre-arm — "we looked, the incident is real, keep going".
    /// @dev THE HIGH THIS CLOSES: `cancelCustodyPreArm` was the only replenishment path and it
    ///      zeroes `custodyPreArmExpiry`, so regaining budget destroyed the active protection and
    ///      opened a window in which curator first-loss could leave ahead of a loss it is cascade
    ///      LAYER 1 for. Reverts with `Curator_NoPreArm` when no budget has been spent.
    function replenishCustodyPreArmBudget() external;

    /// @notice AUDIT FIX (R6-CF1). Current guardian pre-arm: lapse time and CONSECUTIVE budget used
    ///         within the current episode (see `custodyPreArmCooldown`).
    function custodyPreArm() external view returns (uint64 expiry, uint32 count);

    /// @notice AUDIT FIX (R6-CF1). How long one guardian pre-arm lasts. DERIVED from the live
    ///         governance path (`votingDelay + votingPeriod + timelock minDelay`) with the `Config`
    ///         launch parameters as a floor, so it can never expire before governance could
    ///         possibly have ratified it.
    /// @dev Strictly greater than `custodyPreArmGovernancePath()` at every parameterisation.
    function custodyPreArmDuration() external view returns (uint64);

    /// @notice AUDIT FIX (F3-PA-c). The governance path the duration was derived from: the longer
    ///         of the `Config` launch floor and the live reading, bounded by
    ///         `CUSTODY_PRE_ARM_MAX_PATH`.
    function custodyPreArmGovernancePath() external view returns (uint64);

    /// @notice AUDIT FIX (F3-PA-c). False when the path bound BINDS — i.e. one pre-arm window no
    ///         longer outlasts the LIVE governance path and `replenishCustodyPreArmBudget` must
    ///         carry the difference. `script/Validate.s.sol` refuses a deployment where this is
    ///         false, and `preArmCustodyFreeze` emits `CustodyFreezePreArmTruncated` when it arms
    ///         into that regime.
    function custodyPreArmCoversLiveGovernancePath() external view returns (bool);

    /// @notice AUDIT FIX (F3-PA-b). How long layer-1 capital must stand UNFROZEN after a pre-arm
    ///         lapses before the guardian's consecutive budget resets and a new episode may open.
    function custodyPreArmCooldown() external view returns (uint64);

    /// @notice AUDIT FIX (R6-CF1). Wires the ReserveManager whose custody-loss window gates
    ///         withdrawals. Timelocked governance only; zero explicitly unwires (and freezes).
    function setReserveManager(address reserves) external;

    /// @notice AUDIT FIX (R6-CF1). Wires the governor the pre-arm duration is derived from. Zero
    ///         leaves the `Config` launch parameters standing as the sole source.
    function setGovernor(address governor) external;
    function governanceUnpause() external;

    // ── Views ────────────────────────────────────────────────────────────
    /// @notice Current pool balance for a class (18-dec USDfr).
    function poolBalance(uint256 classId) external view returns (uint256);

    /// @notice A curator's current pro-rata stake value in a class.
    /// @dev AUDIT FIX (SWEEP-4 S4-R1, FOUR-INPUT COMPOSITION). Live-round values are exact. A
    ///      closed-round value is a conservative pre-settlement quote because the executable
    ///      remaining/remaining allocation depends on settlement order. Partial holders round
    ///      down; only the unique holder of a snapshot's whole remaining cohort may receive its
    ///      one-unit remainder. It may read zero for sub-wei carry or beyond the bounded walk
    ///      without erasing the claim; call `claimClosedRound` to materialize the exact live stake.
    function postedOf(uint256 classId, address curator) external view returns (uint256);

    /// @notice AUDIT FIX (SWEEP-4 S4-R1). The residual-claim snapshot for a CLOSED round.
    /// @param classId The class.
    /// @param round The closed round.
    /// @return closedShares Shares of `round` that have not yet been settled.
    /// @return carriedShares Shares of round `round + 1` those unsettled shares collectively own.
    function closedRound(uint256 classId, uint256 round)
        external
        view
        returns (uint256 closedShares, uint256 carriedShares);

    /// @notice Required subordination for a class: min(first-loss target, live class
    ///         exposure). Capital up to this level cannot be withdrawn.
    function requiredFirstLoss(uint256 classId) external view returns (uint256);

    /// @notice Withdrawable excess above the subordination requirement.
    function headroom(uint256 classId) external view returns (uint256);

    /// @notice Governance-set first-loss target for a class (ADR-0004: $10M default).
    function firstLossTarget(uint256 classId) external view returns (uint256);

    /// @notice True if `curator` may post first-loss to `classId`.
    function isApprovedCurator(uint256 classId, address curator) external view returns (bool);

    function reserveManager() external view returns (address);
    function modules() external view returns (address usdfr, address registry, address feeVault);
}

src/libraries/Config.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;

/// @title Config
/// @notice Single source of truth for token naming and protocol default parameters
///         (brief Part 12: names are final but kept in one module so a rebrand is a
///         single change).
library Config {
    // ── Token naming (final per brief Part 12) ──────────────────────────
    string internal constant USDFR_NAME = "Forest Road Dollar";
    string internal constant USDFR_SYMBOL = "USDfr";
    string internal constant SUSDFR_NAME = "Staked Forest Road Dollar";
    string internal constant SUSDFR_SYMBOL = "sUSDfr";
    string internal constant GROVE_NAME = "Forest Road Grove";
    string internal constant GROVE_SYMBOL = "GROVE";
    string internal constant SGROVE_NAME = "Staked Forest Road Grove";
    string internal constant SGROVE_SYMBOL = "sGROVE";

    // ── Collateral class IDs (ADR-0003 as amended: all FIVE live at genesis) ──
    uint256 internal constant CLASS_FILM_TAX_CREDITS = 1;
    uint256 internal constant CLASS_RENEWABLE_ENERGY = 2;
    uint256 internal constant CLASS_LIFE_SCIENCES = 3;
    uint256 internal constant CLASS_REAL_ESTATE = 4;
    /// @dev Marked-to-market, related-party class (ADR-0015) — distinct margin/
    ///      liquidation model, NOT the receivable model of classes 1-4.
    uint256 internal constant CLASS_DIGITAL_ASSETS = 5;
    uint256 internal constant NUM_CLASSES = 5;

    // ── Credit-layer defaults (ADR-0004 / ADR-0014; governance-adjustable) ──
    /// @dev USD amounts in 18 decimals (USDfr units).
    uint256 internal constant DEFAULT_FIRST_LOSS_PER_CLASS = 10_000_000e18;
    uint256 internal constant SGROVE_UNBONDING_PERIOD = 21 days;
    // Reward streaming window (ADR-0021 / audit R4-EC1): notified rewards drip linearly
    // over this period rather than distributing instantly, so rewards accrue in real time
    // (Pendle-compatible) and cannot be sandwiched by a deposit-before-harvest. Governance
    // tunable via setRewardsDuration, bounded by SGROVE_MAX_REWARDS_DURATION.
    uint64 internal constant SGROVE_REWARDS_DURATION = 7 days;
    uint64 internal constant SGROVE_MAX_REWARDS_DURATION = 365 days;

    // ── Governance defaults (ADR-0013/0021; FR-controlled at launch) ─────
    /// @dev Fixed at genesis, minted to the Forest Road treasury (ADR-0013).
    uint256 internal constant GROVE_INITIAL_SUPPLY = 1_000_000_000e18;
    uint48 internal constant GOV_VOTING_DELAY = 1 days;
    /// @dev Fresh Ethereum genesis: owner-approved 2026-09-18; existing proxy settings persist.
    uint32 internal constant GOV_VOTING_PERIOD = 2 days;
    uint256 internal constant GOV_PROPOSAL_THRESHOLD = 1_000_000e18; // 0.1% of supply
    uint256 internal constant GOV_QUORUM_FRACTION = 4; // % of total votes
    uint256 internal constant TIMELOCK_MIN_DELAY = 2 days;
    /// @dev C-01 reserve-loss pre-arm floor. The live arm duration is derived from the
    ///      bound Governor and Timelock at arm time and may be longer; this immutable
    ///      floor prevents a broken or shortened timing dependency from failing open.
    uint256 internal constant RESERVE_LOSS_MIN_PREARM_DURATION = 11 days;
    uint256 internal constant RESERVE_LOSS_SCHEDULING_SLACK = 1 days;
    /// @dev Preserve the original curator pre-arm floor when launch voting is shortened.
    ///      Longer live governance schedules still extend the derived protection.
    uint256 internal constant CURATOR_PRE_ARM_MIN_GOVERNANCE_PATH = 10 days;

    /// @dev Protocol fee on distributed interest (waterfall), in bps. Launch default
    ///      is deliberately modest; governance-adjustable; economic-review item.
    uint256 internal constant DEFAULT_PROTOCOL_FEE_BPS = 1_000; // 10% of interest

    /// @dev AUDIT FIX (SWEEP-2 S2-F1) — PERMANENT HARD CAP ON THE INTEREST PROTOCOL FEE.
    ///      DO NOT DELETE AND DO NOT RAISE WITHOUT FOREST ROAD DIRECTION.
    ///
    ///      Before this, `WaterfallEngine.setProtocolFee` was bounded only by `Config.BPS` — it was
    ///      the ONLY fee rate in the protocol with no permanent ceiling, while its three siblings
    ///      (`setOriginationFee` -> `MAX_ORIGINATION_FEE_BPS`, `sUSDfr.setPerformanceFee` ->
    ///      `MAX_PERFORMANCE_FEE_BPS`, `setManagementFee` -> `MAX_MANAGEMENT_FEE_BPS`) all carry
    ///      one and two of those are PUBLISHED to holders (`maxPerformanceFeeBps()`,
    ///      `maxManagementFeeBps()`) and described here as "permanent in v1". MEASURED: 10,000 bps
    ///      was accepted and took the ENTIRE senior yield leg (`toVault` 0, `toFee` the whole
    ///      interest receipt). Because `_routeInterest` takes this fee FIRST, off the same senior
    ///      income stream the vault's 20% performance cap protects, total capture of senior yield
    ///      was reachable AROUND a cap the protocol advertises as permanent — and the fee recipient
    ///      holds plain USDfr, so it is not a cascade layer.
    ///
    ///      The LEVEL mirrors `MAX_PERFORMANCE_FEE_BPS` (20%), i.e. 2x the launch default, which
    ///      is the house convention for "a permanent ceiling with real governance room under it".
    ///      The level is an economic-review item; the EXISTENCE of the ceiling is not.
    uint16 internal constant MAX_PROTOCOL_FEE_BPS = 2_000; // 20% of interest — permanent in v1

    /// @dev Protocol-level performance fee on sUSDfr NAV gains above the global,
    ///      post-fee high-water mark. Launches at 10% and may only be changed
    ///      prospectively by timelocked governance. The hard cap is permanent in v1.
    uint16 internal constant DEFAULT_PERFORMANCE_FEE_BPS = 1_000; // 10% of profit
    uint16 internal constant MAX_PERFORMANCE_FEE_BPS = 2_000; // 20% of profit

    /// @dev Effective-annual sUSDfr management fee on a 365-day basis. Launches disabled
    ///      and may only be enabled prospectively by timelocked governance. Fractional
    ///      periods use geometric retention; the hard cap is permanent in v1.
    uint16 internal constant DEFAULT_MANAGEMENT_FEE_BPS = 0;
    uint16 internal constant MAX_MANAGEMENT_FEE_BPS = 200; // 2% per 365-day year
    uint64 internal constant MANAGEMENT_FEE_YEAR = 365 days;

    /// @dev Origination fee charged at facility funding, in bps of principal (OID
    ///      mechanics: the borrower nets principal minus fee). Market range for the
    ///      book's verticals is ~1-2% (ADR-0019); per-class governance-adjustable,
    ///      capped at MAX_ORIGINATION_FEE_BPS; economic-review item.
    uint16 internal constant DEFAULT_ORIGINATION_FEE_BPS = 200; // 2% of principal (Forest Road direction)
    uint16 internal constant MAX_ORIGINATION_FEE_BPS = 1_000; // 10% hard cap

    /// @dev Margin-call cure window for marked-to-market classes (ADR-0015:
    ///      "hours-to-days"). Governance-adjustable per class; economic-review item.
    uint64 internal constant DEFAULT_MARGIN_CURE_WINDOW = 1 days;

    // ── Liquidity-layer defaults (ADR-0010/0022; governance-adjustable) ──
    /// @dev Settlement HEARTBEAT (ADR-0022): how often `closeEpoch` may run and refresh
    ///      the liquidity budget. Under the ADR-0022 cooldown model this is NOT the
    ///      holding period — `DEFAULT_REDEEM_COOLDOWN` is. The heartbeat must be SHORT
    ///      relative to the cooldown so the effective wait ≈ cooldown (no compounding).
    ///      Heartbeat/liquidity calibration is an economic-review item (ADR-0022 §X.5).
    uint64 internal constant DEFAULT_EPOCH_DURATION = 1 days;
    /// @dev Share of the treasury's idle canonical-USDC liquidity a settlement may
    ///      distribute to the queue PER
    ///      HEARTBEAT, leaving the remainder for direct USDfr redemptions. Rescaled from
    ///      the legacy 50%/30-day batch to preserve ~50%/30-day throughput at a 1-day
    ///      heartbeat (5000/30 ≈ 167). Economic-review item (ADR-0022 §X.5).
    uint16 internal constant DEFAULT_EPOCH_LIQUIDITY_BPS = 167; // ~1.67%/day ≈ 50%/30d

    /// @dev ADR-0022: forced per-request redemption cooldown. A queued redemption cannot
    ///      settle until `requestedAt + DEFAULT_REDEEM_COOLDOWN`. Matches
    ///      `SGROVE_UNBONDING_PERIOD` (21 days) — long enough that a senior cannot exit
    ///      ahead of a foreseeable loss (front-running / loss-dodge defense).
    uint64 internal constant DEFAULT_REDEEM_COOLDOWN = 21 days;

    /// @dev AUDIT FIX (SWEEP-2 CSG-F2) — the UPPER bound on `RedemptionQueue.setRedeemCooldown`.
    ///      The LOWER bound is `DEFAULT_REDEEM_COOLDOWN` itself and is not a separate constant on
    ///      purpose: the G2W relief ramp in `CollateralRegistry.conservativeSeniorMark` is written
    ///      against that exact constant, so the floor must BE it — a second constant is a second
    ///      thing to forget to move (SEAM-1). 180 days is the same order as
    ///      `SGrove.setUnbondingPeriod`'s `AUDIT FIX (L)` ceiling and exists for the same reason:
    ///      an unbounded setter can permanently freeze every queued senior exit by fat finger.
    uint64 internal constant MAX_REDEEM_COOLDOWN = 180 days;

    /// @dev C-1 anti-dust-wedge floor. Minimum REALIZED value (in USDfr, 18 decimals) a
    ///      redemption request must be worth to enter the queue — $1. `closeEpoch` never burns a
    ///      position worth zero at the conservative mark; it stops there, so a sub-wei "dust" head
    ///      could otherwise wedge the queue for the real positions behind it. Barring dust at entry
    ///      makes that wedge reachable only when the exchange rate has collapsed by >1e18x (a
    ///      >99.9999999999999999% senior loss), at which point every realistically-sized position
    ///      is ALSO worth under a wei and halting the queue is the correct behaviour, not griefing.
    ///      Measured at the REALIZED rate (`convertToAssets`), not the conservative one, so a
    ///      declared-but-unrealized impairment does not lock new exits out of the queue.
    ///      Governance-tunable via `RedemptionQueue.setMinRedemptionValue`.
    uint256 internal constant DEFAULT_MIN_REDEMPTION_VALUE = 1e18; // 1 USDfr ($1)

    // ── Optional senior-yield vesting (ADR-0023; governance-adjustable) ──
    /// @dev Realized senior yield may be vested linearly into `sUSDfr.totalAssets()`
    ///      instead of landing as an instant step. Only ALREADY-REALIZED yield can be
    ///      streamed — nothing forward-looking is ever pre-credited, so ADR-0002
    ///      variable-yield pass-through is untouched. Pendle accepts a valid stepwise SY
    ///      exchange rate; smoothing is an optional market-design control against
    ///      payment-timing games and abrupt asset-denominated price moves, not a Pendle
    ///      protocol prerequisite. Forest Road selected instant recognition for launch.
    ///      Governance may enable a non-zero window prospectively after economic review.
    uint64 internal constant DEFAULT_YIELD_VESTING_PERIOD = 0;
    /// @dev Hard ceiling on a newly opened stream. The vault also stores an absolute stream
    ///      deadline that non-zero governance re-tunes and rollovers may shorten but never
    ///      extend, so alternating settings cannot defer the same realized yield indefinitely.
    uint64 internal constant MAX_YIELD_VESTING_PERIOD = 30 days;

    /// @notice RAMP POSTURE (Forest Road direction, 2026-07-21): concentration limits are
    ///         seeded WIDE OPEN so idle deposit capital can be deployed into originations —
    ///         initially a facility to the digital-assets book — without a concentration
    ///         dimension blocking it before the book has any diversity to measure.
    /// @dev At `BPS` (100%) the admission test `exp > limitBps * base / BPS` reduces to
    ///      `exp > base`, and no single dimension can exceed the book, so NOTHING BINDS.
    ///      Two consequences the operator must hold in mind, both stated rather than implied:
    ///        1. Concentration TELEMETRY GOES DARK. `isOverConcentrated`, the drift events and
    ///           `concentrationHeadroom` all measure against the configured limit, so at 100%
    ///           they report "clean" unconditionally. There is no on-chain early warning while
    ///           this posture holds; monitoring must come from the `ExposureRecorded` stream.
    ///        2. RATCHETING DOWN LATER IS A CLIFF. Limits are ADMISSION control and a standing
    ///           breach is permitted (a decrease can never be blocked, or a risk limit could
    ///           veto a loss being realized). So whatever is concentrated when a real limit is
    ///           set will instantly read as breached and be frozen from further growth until
    ///           the book grows around it. Set the first real limits AT or slightly above the
    ///           actual composition at that time, then step down — do not jump straight to the
    ///           target.
    ///      `Validate.s.sol` prints an unmissable posture block whenever this is in force, so
    ///      an unlimited deployment can never produce output identical to a limited one.
    uint16 internal constant RAMP_CONCENTRATION_LIMIT_BPS = 10_000; // 100% = unbounded

    uint256 internal constant BPS = 10_000;

    /// @notice Forward weight, in bps, that an UNATTESTED permissionless past-due mark
    ///         (`DefaultManager.markPastDue`) carries in the conservative redemption NAV,
    ///         relative to an ATTESTED declared default. Used as the fallback whenever
    ///         `DefaultManager`'s governed slot reads zero (see `pastDueWeightBps()`).
    /// @dev OWNER DECISION (Forest Road, 2026-08-07): "An unattested, permissionless past-due
    ///      mark should NOT carry the same forward weight as an attested declared default."
    ///
    ///      DERIVED, NOT INVENTED. The protocol already governs an evidence ladder — but only on
    ///      the marked-to-market side, where the three rungs are per-class registry parameters:
    ///        - `maxLtvBps`         the rung the protocol is willing to be exposed at (healthy);
    ///        - `marginCallLtvBps`  the rung at which a PERMISSIONLESS, REVERSIBLE early warning
    ///                              fires (`marginCall`) — forward impairment weight ZERO, it only
    ///                              starts a cure clock;
    ///        - `liquidationLtvBps` the terminal rung, where `liquidate` records the FULL
    ///                              outstanding into the impairment pool and `realizeLoss` becomes
    ///                              reachable — forward impairment weight ONE.
    ///      `markPastDue` is the receivable-side analogue of the MARGIN-CALL rung: permissionless,
    ///      reversible, early, and strictly BEFORE the terminal attested rung (`declareDefault`).
    ///      Governance placed that early rung exactly half way along the governed deterioration
    ///      band. From the mainnet-v1 class-5 tuple in `script/Deploy.s.sol`
    ///      (maxLtv 5_000, marginCall 6_500, liquidation 8_000):
    ///
    ///          (marginCallLtvBps - maxLtvBps) / (liquidationLtvBps - maxLtvBps)
    ///            = (6_500 - 5_000) / (8_000 - 5_000) = 1_500 / 3_000 = 1/2 = 5_000 bps.
    ///
    ///      WHY NOT THE ADVANCE RATE ALONE. `maxLtvBps`/`ltvBps` cannot supply this weight, and the
    ///      reasoning is recorded here so it is not re-attempted: the advance rate is DEFINED as the
    ///      break-even recovery on the attested claim face (ClaimBridge documents the denominator as
    ///      `principal * BPS / ltvBps`). Senior loss is `max(0, principal - recovery)`, so at a
    ///      recovery equal to the advance rate the loss is identically ZERO — the advance rate
    ///      derives a weight of 0, which re-opens H-5 and D5-03. Worse, every variant that forces a
    ///      positive number out of it (haircut on face, re-advance against carried principal) is
    ///      MONOTONE THE WRONG WAY: it marks a more conservatively underwritten facility harder.
    ///
    ///      DO NOT set this to zero (re-opens H-5: a conflicted servicer can sit on a declaration
    ///      while seniors exit at par) or to `BPS` (restores the defect this constant fixes).
    ///      `CollateralRegistry.setPastDueWeight` enforces both bounds.
    uint256 internal constant DEFAULT_PAST_DUE_WEIGHT_BPS = 5_000; // 50%

    /// @notice sUSDfr entry guard (audit H-3 residual): the maximum ratio of the STRANDED,
    ///         realized-but-unvested yield stream (`sUSDfr.unvestedYield()`) to the DEPOSIT BASE
    ///         (`sUSDfr.totalAssets()`) that vault entry tolerates before `deposit`/`mint` close as
    ///         degenerate.
    /// @dev THE HAZARD (ADR-0023): the vault physically holds realized yield that vests linearly
    ///      into `totalAssets()` over a window and is EXCLUDED from `totalAssets()` until it does.
    ///      Deposits price on `totalAssets()` (OZ's un-overridden `_convertToShares`), so a
    ///      depositor entering while that stranded stream is large relative to the base buys shares
    ///      cheaply and then skims a pro-rata slice of the stream as it vests — extracting from the
    ///      incumbents who funded it. The hazard scales with `unvestedYield() / totalAssets()`, so
    ///      the guard keys on exactly that ratio.
    ///
    ///      CALIBRATION (economic-review item; audit finding #3 re-key from 10 to 3, then audit
    ///      R16-01). `sUSDfr._capStreamToBase` enforces a retention boundary against the ACTUAL
    ///      staked base on both sides of the vault: after every yield delivery AND before every
    ///      queue outflow, at most `1/(K+1)` of physical vault USDfr remains unvested and any
    ///      excess is recognized immediately. A healthy low-staking vault therefore cannot be
    ///      closed by receiving a payment that is large relative to deposits (FRV-FS-03), nor by
    ///      an ordinary settlement shrinking the base under a live stream (RC-03).
    ///      The guard remains meaningful after a senior write-down, which burns the recognized
    ///      base while leaving an already-live stream physically present.
    ///
    ///      WHY 3 AND NOT 10 (the audit residual). The OLD `K = 10` reopened entry the moment the
    ///      ratio fell to 10 — with the stranded stream still 10/11 (~91%) of the vault balance —
    ///      leaving a near-total skim band `(0, 10]` open. It did NOT "close the entire band": near
    ///      the top of that band a fresh depositor could still skim ~91% of the vault as the stream
    ///      vested. Dropping to `K = 3` collapses the open band to `(0, 3)`. `K = 3` bounds the
    ///      excluded stream at the closure point to 3/4 (~75%) of physical vault assets. It is a
    ///      DIMENSIONLESS ratio, not a wei level, so it holds identically at every vault scale.
    ///
    ///      CORRECTION (AUDIT R16-01, HIGH — the previous justification of the open band was
    ///      FALSE; do not restore it). This comment used to argue that the top of the `(0, K]` band
    ///      is "only reachable while the withheld stream is a MAJORITY of the vault, an
    ///      already-catastrophic near-total-write-down state, never a healthy one". That was wrong,
    ///      and `K` was never what bounded a routine deposit's skim. The FRV-FS-03 inflow leg
    ///      created exactly that ratio in a HEALTHY vault: the cap retained `K/(K+1)` of the
    ///      balance, the largest retention the guard tolerates, which parks the vault at precisely
    ///      `unvestedYield() == K * totalAssets()` — and `_isDegenerate`'s strict `>` left entry
    ///      OPEN on that point. Servicing payments are sized off book principal, not off live
    ///      sUSDfr supply, so any payment large relative to the staked base reached it. What bounds
    ///      the routine skim is the CAP's retention target, now `1/(K+1)`: healthy operation parks
    ///      at ratio `1/K`, a factor of `K^2` inside this guard, with a minority (25%) of the
    ///      vault's cash excluded, and the boundary itself is now CLOSED (`>=`). The band between
    ///      `1/K` and `K` is reachable only through a realized loss or a governance re-pricing of
    ///      the vesting window.
    ///
    ///      Kept a constant rather than a governance-tunable for
    ///      this pass: like `SUSDFR_MAX_SHARE_PRICE_COLLAPSE`, it is a defensive safety floor, not an
    ///      operating knob, and adding storage/setter surface to the namespaced vault struct for it
    ///      is unwarranted complexity here; a future pass may promote it to a governed parameter.
    ///      See `SUSDfr._isDegenerate` and `SUSDfr._capStreamToBase`.
    uint256 internal constant SUSDFR_MAX_STRANDED_YIELD_RATIO = 3;

    /// @dev AUDIT R15-01. Vault entry closes once the realized per-share rate has collapsed to
    ///      below `1 / SUSDFR_DEGENERATE_RATE_DIVISOR` of the stored high-water mark.
    ///
    ///      WHY A SECOND BAND IS NEEDED. `SUSDFR_MAX_STRANDED_YIELD_RATIO` above keys on
    ///      `unvestedYield()`, which is identically zero at the launch instant-recognition policy
    ///      (`DEFAULT_YIELD_VESTING_PERIOD == 0`). That band therefore cannot fire at launch,
    ///      leaving only the `totalAssets() == 0` POINT — and one wei of a permissionless USDfr
    ///      transfer steps off a point. `_isDegenerate`'s own rationale states the hazard is the
    ///      whole neighbourhood, not the point; this restores the neighbourhood at every vesting
    ///      setting.
    ///
    ///      WHY PAR IS THE REFERENCE. The stored high-water mark was tried first and rejected:
    ///      `_accrueFees`'s empty-supply branch ratchets it to `(assets + 1) * 1e18` whenever any
    ///      balance exists while `totalSupply() == 0`, so a pre-seed donation could inflate the
    ///      hurdle arbitrarily and then permanently close entry through this band. That is
    ///      harmless while the HWM only suppresses fees, and becomes a brick the moment entry
    ///      depends on it — the invariant suite caught exactly that. Par is derived from the
    ///      token's own decimals, is scale-free, and no actor can move it.
    ///
    ///      WHY 100. The band must separate a catastrophic collapse from a merely bad year, because
    ///      closing entry is a governance event: a vault below 1% of its high-water mark is the
    ///      near-total write-down the guard exists for, while a 50%-drawdown vault stays open to
    ///      new capital. ECONOMIC-REVIEW ITEM, on the same footing as `K = 3` above — the shape is
    ///      a safety floor, but the exact multiple is a judgement about when recapitalization must
    ///      route through governance rather than through an ordinary deposit.
    uint256 internal constant SUSDFR_DEGENERATE_RATE_DIVISOR = 100;
}

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.