Skip to content
Verified contractPartialMIT

NAVOracle

Address0x664ff069206045980dc0af56c2eb656556bac3e5
Balance

0 ETH

 

Transactions

4

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 500 runs
EVM version
shanghai
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,494,356
Creation transaction
0x618555b8dd…ae44e485bc

src/nav/core/NAVOracle.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;

import {AccessManaged} from "@openzeppelin/contracts/access/manager/AccessManaged.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
// solhint-disable-next-line no-global-import — pulls in the shared file-level events/errors too.
import "../interfaces/INAVOracle.sol";
import {NAVPushSinks} from "../sinks/NAVPushSinks.sol";
import {SinkNotFound, SinkSyncFailed} from "../interfaces/NAVSinkTypes.sol";

/**
 * @title NAVOracle — provider-agnostic NAV oracle core (protocol surface only)
 * @notice One per (chain, token): value-safety rails + Protection Mode + timelocked markdown +
 *         round history + downstream sink fan-out. Deliberately carries neither the oracle-network
 *         transport nor the integrator view—both volatile edges are swappable around this stable
 *         core:
 *         - ingestion: a report-provider contract (e.g. {CREReportProvider}) authenticates its
 *           transport (forwarder, workflow identity, report ABI, chain/feed binding) and calls
 *           {submitReport}; swapping oracle networks means authorizing a replacement submitter;
 *         - reads: the integrator-facing view lives in {NAVFeed} behind the {NAVFeedProxy}.
 *
 * @dev NAV monotonicity invariant: no path decreases NAV except {applyMarkdown}, which requires
 *      Protection Mode and the entry-anchored {markdownDelay} timelock (minimum 24 hours).
 *      The automated report path is monotonic non-decreasing; {forceNAVUpdate} is up-or-flat only.
 *
 * @dev Protection Mode blocks automated reports and manual force updates while preserving the
 *      timelocked markdown path. Reports are acknowledged and ignored so the provider can ACK the
 *      transport without a retry storm; absent a markdown, the feed's `updatedAt` remains frozen
 *      and integrator staleness checks can react. Entry is one-shot per governance re-arm, limiting
 *      a compromised on-call key to one freeze before governance intervenes. Production wiring
 *      keeps re-arm and exit governance-only.
 *
 * @dev The velocity guard is a token bucket: budget refills linearly at maxCumulativeBps per
 *      velocityWindow (capped at one bucket). Within an epoch, each accepted report spends the
 *      difference between the cumulative WAD-bps movement from {velocityAnchorNAV} at the new and
 *      current NAV. Those differences telescope, so partitioning one endpoint move cannot reduce
 *      its debit. A new epoch starts only when a report observes a genuine below-cap to full-cap
 *      refill; NAV-changing force writes and markdowns also re-anchor without changing budget.
 *      This is not a hard per-window cap: the sustained rate is maxCumulativeBps per
 *      velocityWindow, the maximum instantaneous burst is one bucket, and the worst case over a
 *      single window (start full, refill, spend again) is up to ~2x maxCumulativeBps. Movement is
 *      accounted to WAD-bps precision instead of whole basis points.
 *
 * @dev All NAV amounts on this contract use 18 decimals.
 */
contract NAVOracle is INAVOracle, NAVPushSinks, ReentrancyGuard {
    /// @notice Basis-point denominator: 100% = 10_000 bps (bands, velocity, and deviation math).
    uint256 public constant MAX_BPS = 10_000;
    /// @notice Maximum configurable normal band (50% in bps) so the value guard can't be disabled by config.
    uint256 public constant MAX_NORMAL_BAND_BPS = 5000;
    /// @notice Minimum time between manual force updates.
    uint256 public constant MIN_FORCE_UPDATE_INTERVAL = 4 hours;
    /// @notice Maximum accepted observation age configurable at deployment.
    uint256 public constant MAX_STALENESS_WINDOW = 7 days;
    /// @notice Maximum velocity-bucket refill period configurable at deployment.
    uint256 public constant MAX_VELOCITY_WINDOW = 30 days;
    /// @notice Minimum velocity-bucket refill period. A shorter period could refill the bucket
    ///         every block and make the cumulative-movement guard ineffective.
    uint256 public constant MIN_VELOCITY_WINDOW = 1 days;
    /// @notice Fixed-point scale for internal velocity accounting. Budget and spend retain up to
    ///         18 decimal places of fractional basis points; smaller amounts round down.
    uint256 private constant BPS_WAD = 1e18;
    /// @notice Minimum interval between markdown executions. This remains enforced after the
    ///         entry review delay, so multiple pre-scheduled markdowns cannot execute together.
    uint256 public constant MIN_MARKDOWN_INTERVAL = 1 days;
    /// @notice Hard floor on the configurable, entry-anchored markdown delay.
    uint256 public constant MIN_MARKDOWN_DELAY_FLOOR = 24 hours;
    /// @notice Ceiling on {markdownDelay}; prevents a deployment value that would make markdowns
    ///         operationally unreachable.
    uint256 public constant MAX_MARKDOWN_DELAY = 30 days;
    /// @notice Floor for markdown targets. It keeps incremental recovery possible under the
    ///         per-write band and remains positive when scaled from 18 to 8 decimals.
    uint256 public constant MIN_MARKDOWN_NAV = 1e12;

    // ----- Immutable configuration -----
    bytes32 public immutable feedId;
    /// @notice Floor applied only to the constructor seed. The report and force paths
    ///         enforce maxNAV + non-decrease + band. Reapplying this floor after a deep markdown
    ///         could block gradual recovery because the first value above the floor may exceed the
    ///         permitted per-write band.
    uint256 public immutable bootstrapMinNAV;
    /// @notice Maximum accepted age of report observations and the constructor seed.
    uint256 public immutable stalenessWindow;
    /// @notice Refill period of the velocity token bucket (one full bucket per window).
    uint256 public immutable velocityWindow;
    /// @notice Automated-report velocity-bucket capacity and refill amount per {velocityWindow}.
    /// @dev Fixed at deployment so elapsed refill always uses one reviewed policy.
    uint256 public immutable maxCumulativeBps;
    /// @notice In-contract markdown timelock anchored to Protection Mode entry. A markdown cannot
    ///         execute until this long after the current episode begins, so a markdown
    ///         pre-scheduled against a predicted future episode id (the AccessManager delay having
    ///         elapsed before the incident) still cannot fire instantly on entry. Makes the review
    ///         window independent of AccessManager configuration; the manager delay may add more
    ///         time but cannot shorten this delay.
    uint256 public immutable markdownDelay;

    // ----- Mutable, governance-tuned value params -----
    /// @notice Absolute upper NAV bound. It is increase-only so governance can raise the ceiling
    ///         without introducing a setter that could block upward reports by lowering it.
    /// @dev This mutable value is a reviewed policy setting, not a bound on root-governance
    ///      authority: an authorized setter can raise it through {setMaxNAV} up to `uint192`.
    uint256 public maxNAV;
    /// @notice Per-write deviation band for the automated report path (bps).
    uint256 public normalBandBps;
    /// @notice Per-write band for the manual force path (bps; >= normalBandBps).
    /// @dev Deployment defaults are policy choices. Root governance can raise this mutable band to
    ///      {MAX_BPS}, permitting a 2x force step while the then-current {maxNAV} still applies.
    uint256 public forceBandBps;

    // ----- Rounds -----
    struct Round {
        uint192 answer; // 18-decimal NAV
        uint64 updatedAt; // block.timestamp when accepted
    }
    mapping(uint80 => Round) private _rounds;
    /// @inheritdoc INAVOracle
    uint80 public latestRound;
    /// @dev Source-data timestamp associated with the current NAV, packed with {latestRound}.
    ///      This is not a monotonic watermark: force writes set it to block time without advancing
    ///      {lastObservationTs}, so a later accepted pre-force observation can move it backward.
    ///      All write paths constrain it to block time or earlier; each stored round's `updatedAt`
    ///      separately records acceptance time.
    uint64 private _currentDataTimestamp;

    // ----- Rails / policy state -----
    /// @notice Remaining velocity budget in WAD-scaled bps (bps × 1e18) as of {velocityLastAccrual}.
    ///         Divide by 1e18 for the human-readable bps figure.
    uint256 public velocityBudgetWad;
    /// @notice Fixed NAV denominator for cumulative automated-report movement in the current
    ///         velocity epoch. Report debits telescope as D(newNAV) - D(currentNAV), where
    ///         D(N) = floor((N - anchor) * 10_000 * 1e18 / anchor).
    /// @dev Initialized to the constructor NAV. It changes only when a report observes a genuine
    ///      below-cap to full-cap refill, a NAV-changing force write succeeds, or a markdown
    ///      succeeds. Re-anchoring does not itself change the stored budget or accrual clock.
    uint256 public velocityAnchorNAV;
    /// @notice Timestamp of the last budget accrual/spend.
    uint256 public velocityLastAccrual;
    /// @notice Automated-report replay watermark. The constructor initializes it from the seed's
    ///         source timestamp; reports advance it strictly; markdowns set it to block.timestamp;
    ///         force writes leave it unchanged. Non-decreasing during this oracle's live operation
    ///         and intentionally distinct from {currentDataTimestamp}.
    uint256 public lastObservationTs;
    /// @notice Timestamp of the last {forceNAVUpdate} (rate-limited by MIN_FORCE_UPDATE_INTERVAL).
    uint256 public lastForceUpdateTs;
    /// @notice Timestamp of the last executed markdown (rate-limited by MIN_MARKDOWN_INTERVAL).
    uint256 public lastMarkdownTs;
    /// @inheritdoc INAVOracle
    bool public protectionMode;
    /// @notice When the current Protection Mode episode began (0 when not active). Anchors the
    ///         entry-relative markdown timelock (readyAt = protectionEnteredAt + markdownDelay; see
    ///         {applyMarkdown}/{isMarkdownExecutable}). NOTE: the markdown *episode-identity* binding
    ///         uses the {protectionEpisodeId} counter, NOT this timestamp — a same-block
    ///         [exit, rearm, enter] governance batch reuses block.timestamp, which would otherwise
    ///         let a stale scheduled markdown from the previous episode execute under the new one.
    uint256 public protectionEnteredAt;
    /// @notice Monotonic Protection Mode episode counter (increments on every entry; never reused).
    ///         The episode id that {applyMarkdown} must be bound to.
    uint256 public protectionEpisodeId;
    /// @notice One-shot arming for Protection Mode entry, consumed by every entry. Production
    ///         wiring restricts re-arming to governance, bounding a compromised on-call key to one
    ///         freeze per re-arm.
    bool public protectionEntryArmed = true;

    struct InitParams {
        bytes32 feedId;
        uint256 bootstrapMinNAV;
        uint256 maxNAV;
        uint256 normalBandBps;
        uint256 forceBandBps;
        uint256 maxCumulativeBps;
        uint256 velocityWindow;
        uint256 stalenessWindow;
        uint256 markdownDelay;
    }

    constructor(
        address initialAuthority,
        InitParams memory p,
        uint256 initialNAV,
        uint256 initialDataTimestamp
    ) AccessManaged(initialAuthority) {
        if (initialAuthority == address(0)) revert ZeroAddress();
        if (p.feedId == bytes32(0)) revert ZeroFeedId();
        // A lower constructor-seed floor could adopt a NAV that truncates to zero on an 8-decimal feed
        // and conflicts with the markdown floor's scaling guarantee.
        if (p.bootstrapMinNAV < MIN_MARKDOWN_NAV || p.bootstrapMinNAV >= p.maxNAV) {
            revert InvalidBounds();
        }
        // Rounds pack the answer into uint192, so every in-bounds value must fit.
        if (p.maxNAV > type(uint192).max) revert InvalidBounds();
        if (p.normalBandBps == 0 || p.normalBandBps > MAX_NORMAL_BAND_BPS) revert InvalidBand();
        if (p.forceBandBps < p.normalBandBps || p.forceBandBps > MAX_BPS) revert InvalidBand();
        // A single band-max report must fit in a full bucket.
        if (p.maxCumulativeBps < p.normalBandBps || p.maxCumulativeBps > MAX_BPS) {
            revert InvalidVelocity();
        }
        if (p.velocityWindow < MIN_VELOCITY_WINDOW || p.velocityWindow > MAX_VELOCITY_WINDOW) {
            revert InvalidVelocity();
        }
        if (p.markdownDelay < MIN_MARKDOWN_DELAY_FLOOR || p.markdownDelay > MAX_MARKDOWN_DELAY) {
            revert InvalidMarkdownDelay();
        }
        if (p.stalenessWindow == 0 || p.stalenessWindow > MAX_STALENESS_WINDOW) {
            revert InvalidStaleness();
        }
        if (initialNAV < p.bootstrapMinNAV || initialNAV > p.maxNAV) {
            revert OutOfBounds(initialNAV);
        }
        if (initialDataTimestamp == 0) revert ZeroObservationTimestamp();
        if (initialDataTimestamp > block.timestamp) {
            revert FutureObservation(initialDataTimestamp, block.timestamp);
        }
        if (initialDataTimestamp + p.stalenessWindow < block.timestamp) {
            revert StaleObservation(initialDataTimestamp);
        }

        feedId = p.feedId;
        bootstrapMinNAV = p.bootstrapMinNAV;
        maxNAV = p.maxNAV;
        normalBandBps = p.normalBandBps;
        forceBandBps = p.forceBandBps;
        maxCumulativeBps = p.maxCumulativeBps;
        velocityWindow = p.velocityWindow;
        stalenessWindow = p.stalenessWindow;
        markdownDelay = p.markdownDelay;

        lastObservationTs = initialDataTimestamp;
        velocityBudgetWad = p.maxCumulativeBps * BPS_WAD;
        velocityAnchorNAV = initialNAV;
        velocityLastAccrual = block.timestamp;
        _record(initialNAV, initialDataTimestamp, UpdateKind.Bootstrap);
        emit Bootstrapped(msg.sender, initialNAV, initialDataTimestamp);
    }

    // =========================================================================
    // Report ingestion (automated path — monotonic non-decreasing; provider-agnostic)
    // =========================================================================

    /// @inheritdoc INAVOracle
    /// @dev `restricted` — wire to the SUBMITTER role, granted to the active report-provider
    ///      contract (e.g. {CREReportProvider}). Swapping oracle networks means deploying and
    ///      authorizing a replacement provider, then revoking the old provider.
    ///
    ///      Value and ordering rails are enforced here. The provider remains responsible for
    ///      authenticating the report and binding the supplied NAV and timestamp to the underlying
    ///      observation.
    ///
    ///      Providers should treat a returned status as acknowledged (no retry for policy freezes
    ///      or permanently unusable observations). A revert remains retryable and should surface
    ///      in monitoring.
    function submitReport(uint256 navValue, uint256 observationTimestamp)
        external
        restricted
        nonReentrant
        returns (SubmitStatus)
    {
        // Policy freeze: acknowledge this report without advancing the feed. If no markdown lands,
        // the unchanged `updatedAt` is the integrator-facing staleness signal.
        if (protectionMode) {
            emit ReportIgnoredInProtection(feedId, navValue, observationTimestamp);
            return SubmitStatus.IgnoredInProtection;
        }

        // Permanently unusable → discard without retry (obsTs monotonicity is also the same-chain
        // replay guard). A future-dated observation may become valid later, so it REVERTS instead.
        if (observationTimestamp <= lastObservationTs) {
            emit ReportDiscarded(
                feedId, navValue, observationTimestamp, NonMonotonicObservation.selector
            );
            return SubmitStatus.DiscardedNonMonotonic;
        }
        if (observationTimestamp > block.timestamp) {
            revert FutureObservation(observationTimestamp, block.timestamp);
        }
        if (observationTimestamp + stalenessWindow < block.timestamp) {
            emit ReportDiscarded(feedId, navValue, observationTimestamp, StaleObservation.selector);
            return SubmitStatus.DiscardedStale;
        }

        (uint256 current, uint256 dev) = _validateUpOrFlat(navValue, normalBandBps);
        _spendVelocity(navValue, current);
        _commit(navValue, observationTimestamp, UpdateKind.Report);
        emit ReportAccepted(feedId, navValue, observationTimestamp, dev);
        return SubmitStatus.Accepted;
    }

    // =========================================================================
    // Manual writes
    // =========================================================================

    /// @notice Restricted manual write for provider outages or recovery upticks. Up-or-flat only.
    /// @dev The observation timestamp is always block.timestamp — the manual path writes "the value
    ///      as of now"; callers cannot supply a separate timestamp.
    ///      This write does not materialize velocity refill or change stored report-path budget. A
    ///      NAV-changing force write re-anchors future cumulative report debit to the written NAV;
    ///      a flat force write leaves the anchor unchanged.
    ///      The force band, maximum NAV, and four-hour cooldown constrain the current configuration,
    ///      but do not contain a compromised governance root that can widen the mutable settings.
    function forceNAVUpdate(uint256 navValue, string calldata reason)
        external
        restricted
        nonReentrant
    {
        if (protectionMode) revert ProtectionModeActive();
        uint256 elapsed = block.timestamp - lastForceUpdateTs;
        if (lastForceUpdateTs > 0 && elapsed < MIN_FORCE_UPDATE_INTERVAL) {
            revert ForceUpdateTooFrequent(elapsed, MIN_FORCE_UPDATE_INTERVAL);
        }
        (uint256 current,) = _validateUpOrFlat(navValue, forceBandBps);
        if (navValue != current) velocityAnchorNAV = navValue;
        lastForceUpdateTs = block.timestamp;
        _commit(navValue, block.timestamp, UpdateKind.Force);
        emit NAVForceUpdated(msg.sender, navValue, block.timestamp, reason);
    }

    /// @notice Execute a write-down—the only decrease path. `restricted`; gated by the
    ///         entry-anchored {markdownDelay}. Production wiring should add an AccessManager
    ///         execution delay for the markdown selector as defense in depth.
    /// @param protectionEpisode Must equal the current {protectionEpisodeId}. This binds the
    ///        markdown to the specific protection episode it was scheduled under: a scheduled-but-
    ///        unexecuted markdown from a stood-down incident stays live in the AccessManager and
    ///        would otherwise become executable again the moment a later, unrelated incident enters
    ///        Protection Mode — firing a stale impairment with no fresh review window. With the
    ///        binding, exit + re-entry changes the episode and the stale op reverts. (Still cancel
    ///        retired markdowns via AccessManager.cancel as hygiene.)
    /// @dev When an AccessManager delay is configured and elapsed, prefer calling this function
    ///      directly. AccessManaged consumes the scheduled operation while preserving the signer
    ///      as `msg.sender` and `NewRound.startedBy`; routing through AccessManager.execute records
    ///      the manager as the caller instead.
    function applyMarkdown(uint256 navValue, uint256 protectionEpisode, string calldata reason)
        external
        restricted
        nonReentrant
    {
        if (!protectionMode) revert ProtectionModeNotActive();
        if (protectionEpisode != protectionEpisodeId) {
            revert MarkdownEpisodeMismatch(protectionEpisode, protectionEpisodeId);
        }
        // markdownDelay must pass from this episode's entry, so a
        // markdown pre-scheduled (manager delay pre-elapsed) against a predicted episode cannot fire
        // the instant protection is entered. protectionEnteredAt is the current episode's entry time.
        uint256 readyAt = protectionEnteredAt + markdownDelay;
        if (block.timestamp < readyAt) revert MarkdownDelayNotElapsed(readyAt, block.timestamp);
        uint256 sinceLast = block.timestamp - lastMarkdownTs;
        if (lastMarkdownTs > 0 && sinceLast < MIN_MARKDOWN_INTERVAL) {
            revert MarkdownTooFrequent(sinceLast, MIN_MARKDOWN_INTERVAL);
        }
        uint256 current = _currentNav();
        if (navValue >= current) revert MarkdownMustDecrease(navValue, current);
        // Keep the scaled feed answer nonzero and recovery increments practical.
        if (navValue < MIN_MARKDOWN_NAV) revert MarkdownBelowFloor(navValue, MIN_MARKDOWN_NAV);
        // Markdown preserves the stored report-path budget and accrual clock while re-anchoring
        // future cumulative report debit to the impaired NAV.
        velocityAnchorNAV = navValue;
        lastMarkdownTs = block.timestamp;
        uint80 roundId = _commit(navValue, block.timestamp, UpdateKind.Markdown);
        emit MarkdownApplied(roundId, current, navValue, reason);
    }

    // =========================================================================
    // Protection Mode
    // =========================================================================

    /// @notice Enter Protection Mode. Configure this selector for governance and approved on-call
    ///         keys with zero delay. Every entry consumes the one-shot arming; production wiring
    ///         keeps re-arming governance-only.
    function enterProtectionMode(string calldata reason) external restricted {
        if (protectionMode) revert ProtectionModeActive();
        if (!protectionEntryArmed) revert ProtectionEntryNotArmed();
        protectionEntryArmed = false;
        protectionMode = true;
        protectionEnteredAt = block.timestamp;
        ++protectionEpisodeId; // A counter gives same-block re-entry a distinct episode id.
        emit ProtectionModeEntered(msg.sender, protectionEpisodeId, reason);
    }

    /// @notice Exit Protection Mode. Production wiring should keep this governance-only because
    ///         incident exits require sign-off.
    function exitProtectionMode() external restricted {
        if (!protectionMode) revert ProtectionModeNotActive();
        protectionMode = false;
        protectionEnteredAt = 0;
        emit ProtectionModeExited(msg.sender);
    }

    /// @notice Re-arm the protection-entry trigger. Production wiring should keep this
    ///         governance-only. Refused while protection is active so a live freeze cannot be
    ///         immediately re-armed.
    function rearmProtectionEntry() external restricted {
        if (protectionMode) revert ProtectionModeActive();
        protectionEntryArmed = true;
        emit ProtectionEntryRearmed(msg.sender);
    }

    // =========================================================================
    // Internal write machinery
    // =========================================================================

    /// @dev maxNAV bound + up-or-flat (non-decrease) + per-write band vs current NAV. Returns
    ///      the current NAV and deviation (bps) so callers do not need to reload the same round.
    function _validateUpOrFlat(uint256 navValue, uint256 bandBps)
        private
        view
        returns (uint256 current, uint256 deviationBps)
    {
        // Only maxNAV applies here; see {bootstrapMinNAV} for why report/force paths have no floor.
        if (navValue > maxNAV) revert OutOfBounds(navValue);
        current = _currentNav();
        if (navValue < current) revert NAVMustNotDecrease(navValue, current);
        // Round upward so a sub-basis-point remainder cannot slip past the configured band.
        deviationBps = Math.mulDiv(navValue - current, MAX_BPS, current, Math.Rounding.Ceil);
        if (deviationBps > bandBps) revert DeviationExceeded(navValue, current, deviationBps);
    }

    /// @dev Accrue and spend automated-report movement in one token-bucket operation. Under a fixed
    ///      anchor A, charge D(new) - D(current), where
    ///      D(N) = floor((N - A) * MAX_BPS * BPS_WAD / A). The cumulative floors make report
    ///      debits telescope exactly within an epoch instead of leaking one rounding remainder per
    ///      report. A report starts a new epoch at the pre-report current NAV only when stored
    ///      budget was below capacity and elapsed refill has filled the exact deficit. Merely
    ///      remaining at full capacity does not re-anchor.
    function _spendVelocity(uint256 navValue, uint256 current) private {
        uint256 capWad = maxCumulativeBps * BPS_WAD;
        uint256 storedWad = velocityBudgetWad;
        uint256 storedAnchor = velocityAnchorNAV;
        uint256 anchor = storedAnchor;
        uint256 availableWad;

        if (storedWad == capWad) {
            // Already full is still the same epoch. Re-anchoring here would let zero-debit reports
            // repeatedly move the denominator while retaining the full bucket.
            availableWad = capWad;
        } else {
            uint256 missingWad = capWad - storedWad;
            uint256 secondsToFull =
                Math.mulDiv(missingWad, velocityWindow, capWad, Math.Rounding.Ceil);
            uint256 elapsed = block.timestamp - velocityLastAccrual;

            if (elapsed >= secondsToFull) {
                availableWad = capWad;
                anchor = current;
            } else {
                uint256 refillWad = Math.mulDiv(capWad, elapsed, velocityWindow);
                // elapsed < ceil(missing * window / cap) implies refillWad < missingWad.
                availableWad = storedWad + refillWad;
            }
        }

        // The report path has already enforced anchor <= current <= navValue. Math.mulDiv avoids
        // intermediate overflow and rounds each cumulative value down to WAD-bps precision.
        uint256 scale = MAX_BPS * BPS_WAD;
        uint256 cumulativeCurrentWad =
            current == anchor ? 0 : Math.mulDiv(current - anchor, scale, anchor);
        uint256 cumulativeNewWad = Math.mulDiv(navValue - anchor, scale, anchor);
        uint256 moveWad = cumulativeNewWad - cumulativeCurrentWad;
        if (moveWad > availableWad) {
            revert VelocityExceeded(navValue, moveWad, availableWad);
        }
        uint256 remainingWad = availableWad - moveWad;
        if (anchor != storedAnchor) velocityAnchorNAV = anchor;
        if (remainingWad != storedWad) velocityBudgetWad = remainingWad;
        velocityLastAccrual = block.timestamp;
    }

    /// @dev Store a round and emit the canonical event triple: NAVUpdated plus the
    ///      Chainlink-canonical NewRound/AnswerUpdated for indexer tooling (18-dec answer — emitted
    ///      here because the view-only NAVFeed cannot emit; see the interface note). The single
    ///      source of truth for round recording, shared by _commit and the constructor seed.
    function _record(uint256 navValue, uint256 dataTimestamp, UpdateKind kind)
        private
        returns (uint80 roundId)
    {
        roundId = ++latestRound;
        _rounds[roundId] = Round(uint192(navValue), uint64(block.timestamp));
        _currentDataTimestamp = uint64(dataTimestamp);
        emit NAVUpdated(roundId, navValue, dataTimestamp, kind);
        emit NewRound(roundId, msg.sender, block.timestamp);
        emit AnswerUpdated(int256(navValue), roundId, block.timestamp);
    }

    /// @dev Full write commit: advance the observation clock (report AND markdown only — see
    ///      below), record the round, then fan out to sinks LAST (checks-effects-interactions).
    function _commit(uint256 navValue, uint256 dataTimestamp, UpdateKind kind)
        private
        returns (uint80 roundId)
    {
        // Reports and markdowns advance the observation clock; force writes do not.
        //  - report: preserves ordering and replay protection for automated observations.
        //  - markdown: sets the clock to block.timestamp so a stale pre-incident report
        //    (higher, still within a long stalenessWindow) cannot be accepted after exit and
        //    reverse the write-down. A genuine post-incident report is observed later, so it still
        //    lands.
        //  - force: must not advance it, or a real report observed just before an outage-recovery
        //    force write would be wrongly discarded on resume.
        if (kind == UpdateKind.Report || kind == UpdateKind.Markdown) {
            lastObservationTs = dataTimestamp;
        }
        roundId = _record(navValue, dataTimestamp, kind);
        _pushSinks(navValue);
    }

    function _currentNav() private view returns (uint256) {
        return _rounds[latestRound].answer;
    }

    // =========================================================================
    // Governance config
    // =========================================================================

    /// @notice Raise the absolute NAV ceiling. The setter is increase-only because lowering the
    ///         ceiling to or below the current NAV could block future upward reports.
    function setMaxNAV(uint256 newMaxNAV) external restricted {
        if (newMaxNAV <= maxNAV || newMaxNAV > type(uint192).max) revert InvalidBounds();
        emit MaxNAVUpdated(maxNAV, newMaxNAV);
        maxNAV = newMaxNAV;
    }

    function setNormalBandBps(uint256 bps) external restricted {
        if (bps == 0 || bps > MAX_NORMAL_BAND_BPS || bps > forceBandBps || bps > maxCumulativeBps) {
            revert InvalidBand();
        }
        emit NormalBandUpdated(normalBandBps, bps);
        normalBandBps = bps;
    }

    function setForceBandBps(uint256 bps) external restricted {
        if (bps < normalBandBps || bps > MAX_BPS) revert InvalidBand();
        emit ForceBandUpdated(forceBandBps, bps);
        forceBandBps = bps;
    }

    // =========================================================================
    // Views — protocol surface (18 decimals)
    // =========================================================================

    /// @notice Return the current NAV and the source-data timestamp associated with that value.
    /// @dev Round 1 is created by the constructor, so every deployed instance has current data.
    function getCurrentNAV() external view returns (uint256 nav, uint256 timestamp) {
        Round storage r = _rounds[latestRound];
        return (r.answer, _currentDataTimestamp);
    }

    /// @inheritdoc INAVOracle
    function navDecimals() external pure returns (uint8) {
        return 18;
    }

    /// @inheritdoc INAVOracle
    function currentDataTimestamp() external view returns (uint256) {
        return _currentDataTimestamp;
    }

    /// @notice Restricted retry intended for governance: push the current NAV to one registered
    ///         sink after a revoked role, pause, or outage caused {SinkPushFailed}.
    ///         Unlike ordinary best-effort fan-out, this explicit catch-up reverts if delivery
    ///         fails so automation cannot record an unsuccessful recovery as complete. The caller
    ///         must still supply enough gas for the configured sink-call budget. This exact replay
    ///         cannot bypass receiver-specific authorization or validation. Recovery beyond exact
    ///         replay is target-specific; use only the procedure approved for that sink family.
    function syncSink(address target) external restricted nonReentrant {
        if (!_hasSink(target)) revert SinkNotFound(target);
        uint256 nav = _currentNav();
        if (!_pushOne(target, nav)) revert SinkSyncFailed(target, nav);
    }

    /// @notice Whether all oracle-local episode and timing gates pass for `episode`. This does not
    ///         check AccessManager authorization or scheduling, nor proposal-specific target
    ///         constraints such as decrease and floor requirements.
    function isMarkdownExecutable(uint256 episode) external view returns (bool) {
        if (!protectionMode || episode != protectionEpisodeId) return false;
        if (block.timestamp < protectionEnteredAt + markdownDelay) return false;
        if (lastMarkdownTs != 0 && block.timestamp - lastMarkdownTs < MIN_MARKDOWN_INTERVAL) {
            return false;
        }
        return true;
    }

    /// @inheritdoc INAVOracle
    function getRound(uint80 roundId) external view returns (uint256 answer, uint256 updatedAt) {
        Round storage r = _rounds[roundId];
        if (r.updatedAt == 0) revert NoData(roundId);
        return (r.answer, r.updatedAt);
    }
}

lib/openzeppelin-contracts/contracts/access/manager/AccessManaged.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/manager/AccessManaged.sol)

pragma solidity ^0.8.20;

import {AuthorityUtils} from "./AuthorityUtils.sol";
import {IAccessManager} from "./IAccessManager.sol";
import {IAccessManaged} from "./IAccessManaged.sol";
import {Context} from "../../utils/Context.sol";

/**
 * @dev This contract module makes available a {restricted} modifier. Functions decorated with this modifier will be
 * permissioned according to an "authority": a contract like {AccessManager} that follows the {IAuthority} interface,
 * implementing a policy that allows certain callers to access certain functions.
 *
 * IMPORTANT: The `restricted` modifier should never be used on `internal` functions, judiciously used in `public`
 * functions, and ideally only used in `external` functions. See {restricted}.
 */
abstract contract AccessManaged is Context, IAccessManaged {
    address private _authority;

    bool private _consumingSchedule;

    /**
     * @dev Initializes the contract connected to an initial authority.
     */
    constructor(address initialAuthority) {
        _setAuthority(initialAuthority);
    }

    /**
     * @dev Restricts access to a function as defined by the connected Authority for this contract and the
     * caller and selector of the function that entered the contract.
     *
     * [IMPORTANT]
     * ====
     * In general, this modifier should only be used on `external` functions. It is okay to use it on `public`
     * functions that are used as external entry points and are not called internally. Unless you know what you're
     * doing, it should never be used on `internal` functions. Failure to follow these rules can have critical security
     * implications! This is because the permissions are determined by the function that entered the contract, i.e. the
     * function at the bottom of the call stack, and not the function where the modifier is visible in the source code.
     * ====
     *
     * [WARNING]
     * ====
     * Avoid adding this modifier to the https://docs.soliditylang.org/en/v0.8.20/contracts.html#receive-ether-function[`receive()`]
     * function or the https://docs.soliditylang.org/en/v0.8.20/contracts.html#fallback-function[`fallback()`]. These
     * functions are the only execution paths where a function selector cannot be unambiguously determined from the calldata
     * since the selector defaults to `0x00000000` in the `receive()` function and similarly in the `fallback()` function
     * if no calldata is provided. (See {_checkCanCall}).
     *
     * The `receive()` function will always panic whereas the `fallback()` may panic depending on the calldata length.
     * ====
     */
    modifier restricted() {
        _checkCanCall(_msgSender(), _msgData());
        _;
    }

    /// @inheritdoc IAccessManaged
    function authority() public view virtual returns (address) {
        return _authority;
    }

    /// @inheritdoc IAccessManaged
    function setAuthority(address newAuthority) public virtual {
        address caller = _msgSender();
        if (caller != authority()) {
            revert AccessManagedUnauthorized(caller);
        }
        if (newAuthority.code.length == 0) {
            revert AccessManagedInvalidAuthority(newAuthority);
        }
        _setAuthority(newAuthority);
    }

    /// @inheritdoc IAccessManaged
    function isConsumingScheduledOp() public view returns (bytes4) {
        return _consumingSchedule ? this.isConsumingScheduledOp.selector : bytes4(0);
    }

    /**
     * @dev Transfers control to a new authority. Internal function with no access restriction. Allows bypassing the
     * permissions set by the current authority.
     */
    function _setAuthority(address newAuthority) internal virtual {
        _authority = newAuthority;
        emit AuthorityUpdated(newAuthority);
    }

    /**
     * @dev Reverts if the caller is not allowed to call the function identified by a selector. Panics if the calldata
     * is less than 4 bytes long.
     */
    function _checkCanCall(address caller, bytes calldata data) internal virtual {
        (bool immediate, uint32 delay) = AuthorityUtils.canCallWithDelay(
            authority(),
            caller,
            address(this),
            bytes4(data[0:4])
        );
        if (!immediate) {
            if (delay > 0) {
                _consumingSchedule = true;
                IAccessManager(authority()).consumeScheduledOp(caller, data);
                _consumingSchedule = false;
            } else {
                revert AccessManagedUnauthorized(caller);
            }
        }
    }
}

lib/openzeppelin-contracts/contracts/access/manager/AuthorityUtils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (access/manager/AuthorityUtils.sol)

pragma solidity ^0.8.20;

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

library AuthorityUtils {
    /**
     * @dev Since `AccessManager` implements an extended IAuthority interface, invoking `canCall` with backwards compatibility
     * for the preexisting `IAuthority` interface requires special care to avoid reverting on insufficient return data.
     * This helper function takes care of invoking `canCall` in a backwards compatible way without reverting.
     */
    function canCallWithDelay(
        address authority,
        address caller,
        address target,
        bytes4 selector
    ) internal view returns (bool immediate, uint32 delay) {
        bytes memory data = abi.encodeCall(IAuthority.canCall, (caller, target, selector));

        assembly ("memory-safe") {
            mstore(0x00, 0x00)
            mstore(0x20, 0x00)

            if staticcall(gas(), authority, add(data, 0x20), mload(data), 0x00, 0x40) {
                immediate := mload(0x00)
                delay := mload(0x20)

                // If delay does not fit in a uint32, return 0 (no delay)
                // equivalent to: if gt(delay, 0xFFFFFFFF) { delay := 0 }
                delay := mul(delay, iszero(shr(32, delay)))
            }
        }
    }
}

lib/openzeppelin-contracts/contracts/access/manager/IAccessManaged.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/manager/IAccessManaged.sol)

pragma solidity >=0.8.4;

interface IAccessManaged {
    /**
     * @dev Authority that manages this contract was updated.
     */
    event AuthorityUpdated(address authority);

    error AccessManagedUnauthorized(address caller);
    error AccessManagedRequiredDelay(address caller, uint32 delay);
    error AccessManagedInvalidAuthority(address authority);

    /**
     * @dev Returns the current authority.
     */
    function authority() external view returns (address);

    /**
     * @dev Transfers control to a new authority. The caller must be the current authority.
     */
    function setAuthority(address) external;

    /**
     * @dev Returns true only in the context of a delayed restricted call, at the moment that the scheduled operation is
     * being consumed. Prevents denial of service for delayed restricted calls in the case that the contract performs
     * attacker controlled calls.
     */
    function isConsumingScheduledOp() external view returns (bytes4);
}

lib/openzeppelin-contracts/contracts/access/manager/IAccessManager.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/manager/IAccessManager.sol)

pragma solidity >=0.8.4;

interface IAccessManager {
    /**
     * @dev A delayed operation was scheduled.
     */
    event OperationScheduled(
        bytes32 indexed operationId,
        uint32 indexed nonce,
        uint48 schedule,
        address caller,
        address target,
        bytes data
    );

    /**
     * @dev A scheduled operation was executed.
     */
    event OperationExecuted(bytes32 indexed operationId, uint32 indexed nonce);

    /**
     * @dev A scheduled operation was canceled.
     */
    event OperationCanceled(bytes32 indexed operationId, uint32 indexed nonce);

    /**
     * @dev Informational labelling for a roleId.
     */
    event RoleLabel(uint64 indexed roleId, string label);

    /**
     * @dev Emitted when `account` is granted `roleId`.
     *
     * NOTE: The meaning of the `since` argument depends on the `newMember` argument.
     * If the role is granted to a new member, the `since` argument indicates when the account becomes a member of the role,
     * otherwise it indicates the execution delay for this account and roleId is updated.
     */
    event RoleGranted(uint64 indexed roleId, address indexed account, uint32 delay, uint48 since, bool newMember);

    /**
     * @dev Emitted when `account` membership or `roleId` is revoked. Unlike granting, revoking is instantaneous.
     */
    event RoleRevoked(uint64 indexed roleId, address indexed account);

    /**
     * @dev Role acting as admin over a given `roleId` is updated.
     */
    event RoleAdminChanged(uint64 indexed roleId, uint64 indexed admin);

    /**
     * @dev Role acting as guardian over a given `roleId` is updated.
     */
    event RoleGuardianChanged(uint64 indexed roleId, uint64 indexed guardian);

    /**
     * @dev Grant delay for a given `roleId` will be updated to `delay` when `since` is reached.
     */
    event RoleGrantDelayChanged(uint64 indexed roleId, uint32 delay, uint48 since);

    /**
     * @dev Target mode is updated (true = closed, false = open).
     */
    event TargetClosed(address indexed target, bool closed);

    /**
     * @dev Role required to invoke `selector` on `target` is updated to `roleId`.
     */
    event TargetFunctionRoleUpdated(address indexed target, bytes4 selector, uint64 indexed roleId);

    /**
     * @dev Admin delay for a given `target` will be updated to `delay` when `since` is reached.
     */
    event TargetAdminDelayUpdated(address indexed target, uint32 delay, uint48 since);

    error AccessManagerAlreadyScheduled(bytes32 operationId);
    error AccessManagerNotScheduled(bytes32 operationId);
    error AccessManagerNotReady(bytes32 operationId);
    error AccessManagerExpired(bytes32 operationId);
    error AccessManagerLockedRole(uint64 roleId);
    error AccessManagerBadConfirmation();
    error AccessManagerUnauthorizedAccount(address msgsender, uint64 roleId);
    error AccessManagerUnauthorizedCall(address caller, address target, bytes4 selector);
    error AccessManagerUnauthorizedConsume(address target);
    error AccessManagerUnauthorizedCancel(address msgsender, address caller, address target, bytes4 selector);
    error AccessManagerInvalidInitialAdmin(address initialAdmin);

    /**
     * @dev Check if an address (`caller`) is authorised to call a given function on a given contract directly (with
     * no restriction). Additionally, it returns the delay needed to perform the call indirectly through the {schedule}
     * & {execute} workflow.
     *
     * This function is usually called by the targeted contract to control immediate execution of restricted functions.
     * Therefore we only return true if the call can be performed without any delay. If the call is subject to a
     * previously set delay (not zero), then the function should return false and the caller should schedule the operation
     * for future execution.
     *
     * If `allowed` is true, the delay can be disregarded and the operation can be immediately executed, otherwise
     * the operation can be executed if and only if delay is greater than 0.
     *
     * NOTE: The IAuthority interface does not include the `uint32` delay. This is an extension of that interface that
     * is backward compatible. Some contracts may thus ignore the second return argument. In that case they will fail
     * to identify the indirect workflow, and will consider calls that require a delay to be forbidden.
     *
     * NOTE: This function does not report the permissions of the admin functions in the manager itself. These are defined by the
     * {AccessManager} documentation.
     */
    function canCall(
        address caller,
        address target,
        bytes4 selector
    ) external view returns (bool allowed, uint32 delay);

    /**
     * @dev Expiration delay for scheduled proposals. Defaults to 1 week.
     *
     * IMPORTANT: Avoid overriding the expiration with 0. Otherwise every contract proposal will be expired immediately,
     * disabling any scheduling usage.
     */
    function expiration() external view returns (uint32);

    /**
     * @dev Minimum setback for all delay updates, with the exception of execution delays. It
     * can be increased without setback (and reset via {revokeRole} in the case event of an
     * accidental increase). Defaults to 5 days.
     */
    function minSetback() external view returns (uint32);

    /**
     * @dev Get whether the contract is closed disabling any access. Otherwise role permissions are applied.
     *
     * NOTE: When the manager itself is closed, admin functions are still accessible to avoid locking the contract.
     */
    function isTargetClosed(address target) external view returns (bool);

    /**
     * @dev Get the role required to call a function.
     */
    function getTargetFunctionRole(address target, bytes4 selector) external view returns (uint64);

    /**
     * @dev Get the admin delay for a target contract. Changes to contract configuration are subject to this delay.
     */
    function getTargetAdminDelay(address target) external view returns (uint32);

    /**
     * @dev Get the id of the role that acts as an admin for the given role.
     *
     * The admin permission is required to grant the role, revoke the role and update the execution delay to execute
     * an operation that is restricted to this role.
     */
    function getRoleAdmin(uint64 roleId) external view returns (uint64);

    /**
     * @dev Get the role that acts as a guardian for a given role.
     *
     * The guardian permission allows canceling operations that have been scheduled under the role.
     */
    function getRoleGuardian(uint64 roleId) external view returns (uint64);

    /**
     * @dev Get the role current grant delay.
     *
     * Its value may change at any point without an event emitted following a call to {setGrantDelay}.
     * Changes to this value, including effect timepoint are notified in advance by the {RoleGrantDelayChanged} event.
     */
    function getRoleGrantDelay(uint64 roleId) external view returns (uint32);

    /**
     * @dev Get the access details for a given account for a given role. These details include the timepoint at which
     * membership becomes active, and the delay applied to all operation by this user that requires this permission
     * level.
     *
     * Returns:
     * [0] Timestamp at which the account membership becomes valid. 0 means role is not granted.
     * [1] Current execution delay for the account.
     * [2] Pending execution delay for the account.
     * [3] Timestamp at which the pending execution delay will become active. 0 means no delay update is scheduled.
     */
    function getAccess(
        uint64 roleId,
        address account
    ) external view returns (uint48 since, uint32 currentDelay, uint32 pendingDelay, uint48 effect);

    /**
     * @dev Check if a given account currently has the permission level corresponding to a given role. Note that this
     * permission might be associated with an execution delay. {getAccess} can provide more details.
     */
    function hasRole(uint64 roleId, address account) external view returns (bool isMember, uint32 executionDelay);

    /**
     * @dev Give a label to a role, for improved role discoverability by UIs.
     *
     * Requirements:
     *
     * - the caller must be a global admin
     *
     * Emits a {RoleLabel} event.
     */
    function labelRole(uint64 roleId, string calldata label) external;

    /**
     * @dev Add `account` to `roleId`, or change its execution delay.
     *
     * This gives the account the authorization to call any function that is restricted to this role. An optional
     * execution delay (in seconds) can be set. If that delay is non 0, the user is required to schedule any operation
     * that is restricted to members of this role. The user will only be able to execute the operation after the delay has
     * passed, before it has expired. During this period, admin and guardians can cancel the operation (see {cancel}).
     *
     * If the account has already been granted this role, the execution delay will be updated. This update is not
     * immediate and follows the delay rules. For example, if a user currently has a delay of 3 hours, and this is
     * called to reduce that delay to 1 hour, the new delay will take some time to take effect, enforcing that any
     * operation executed in the 3 hours that follows this update was indeed scheduled before this update.
     *
     * Requirements:
     *
     * - the caller must be an admin for the role (see {getRoleAdmin})
     * - granted role must not be the `PUBLIC_ROLE`
     *
     * Emits a {RoleGranted} event.
     */
    function grantRole(uint64 roleId, address account, uint32 executionDelay) external;

    /**
     * @dev Remove an account from a role, with immediate effect. If the account does not have the role, this call has
     * no effect.
     *
     * Requirements:
     *
     * - the caller must be an admin for the role (see {getRoleAdmin})
     * - revoked role must not be the `PUBLIC_ROLE`
     *
     * Emits a {RoleRevoked} event if the account had the role.
     */
    function revokeRole(uint64 roleId, address account) external;

    /**
     * @dev Renounce role permissions for the calling account with immediate effect. If the sender is not in
     * the role this call has no effect.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * Emits a {RoleRevoked} event if the account had the role.
     */
    function renounceRole(uint64 roleId, address callerConfirmation) external;

    /**
     * @dev Change admin role for a given role.
     *
     * Requirements:
     *
     * - the caller must be a global admin
     *
     * Emits a {RoleAdminChanged} event
     */
    function setRoleAdmin(uint64 roleId, uint64 admin) external;

    /**
     * @dev Change guardian role for a given role.
     *
     * Requirements:
     *
     * - the caller must be a global admin
     *
     * Emits a {RoleGuardianChanged} event
     */
    function setRoleGuardian(uint64 roleId, uint64 guardian) external;

    /**
     * @dev Update the delay for granting a `roleId`.
     *
     * Requirements:
     *
     * - the caller must be a global admin
     *
     * Emits a {RoleGrantDelayChanged} event.
     */
    function setGrantDelay(uint64 roleId, uint32 newDelay) external;

    /**
     * @dev Set the role required to call functions identified by the `selectors` in the `target` contract.
     *
     * Requirements:
     *
     * - the caller must be a global admin
     *
     * Emits a {TargetFunctionRoleUpdated} event per selector.
     */
    function setTargetFunctionRole(address target, bytes4[] calldata selectors, uint64 roleId) external;

    /**
     * @dev Set the delay for changing the configuration of a given target contract.
     *
     * Requirements:
     *
     * - the caller must be a global admin
     *
     * Emits a {TargetAdminDelayUpdated} event.
     */
    function setTargetAdminDelay(address target, uint32 newDelay) external;

    /**
     * @dev Set the closed flag for a contract.
     *
     * Closing the manager itself won't disable access to admin methods to avoid locking the contract.
     *
     * Requirements:
     *
     * - the caller must be a global admin
     *
     * Emits a {TargetClosed} event.
     */
    function setTargetClosed(address target, bool closed) external;

    /**
     * @dev Return the timepoint at which a scheduled operation will be ready for execution. This returns 0 if the
     * operation is not yet scheduled, has expired, was executed, or was canceled.
     */
    function getSchedule(bytes32 id) external view returns (uint48);

    /**
     * @dev Return the nonce for the latest scheduled operation with a given id. Returns 0 if the operation has never
     * been scheduled.
     */
    function getNonce(bytes32 id) external view returns (uint32);

    /**
     * @dev Schedule a delayed operation for future execution, and return the operation identifier. It is possible to
     * choose the timestamp at which the operation becomes executable as long as it satisfies the execution delays
     * required for the caller. The special value zero will automatically set the earliest possible time.
     *
     * Returns the `operationId` that was scheduled. Since this value is a hash of the parameters, it can reoccur when
     * the same parameters are used; if this is relevant, the returned `nonce` can be used to uniquely identify this
     * scheduled operation from other occurrences of the same `operationId` in invocations of {execute} and {cancel}.
     *
     * Emits a {OperationScheduled} event.
     *
     * NOTE: It is not possible to concurrently schedule more than one operation with the same `target` and `data`. If
     * this is necessary, a random byte can be appended to `data` to act as a salt that will be ignored by the target
     * contract if it is using standard Solidity ABI encoding.
     */
    function schedule(
        address target,
        bytes calldata data,
        uint48 when
    ) external returns (bytes32 operationId, uint32 nonce);

    /**
     * @dev Execute a function that is delay restricted, provided it was properly scheduled beforehand, or the
     * execution delay is 0.
     *
     * Returns the nonce that identifies the previously scheduled operation that is executed, or 0 if the
     * operation wasn't previously scheduled (if the caller doesn't have an execution delay).
     *
     * Emits an {OperationExecuted} event only if the call was scheduled and delayed.
     */
    function execute(address target, bytes calldata data) external payable returns (uint32);

    /**
     * @dev Cancel a scheduled (delayed) operation. Returns the nonce that identifies the previously scheduled
     * operation that is cancelled.
     *
     * Requirements:
     *
     * - the caller must be the proposer, a guardian of the targeted function, or a global admin
     *
     * Emits a {OperationCanceled} event.
     */
    function cancel(address caller, address target, bytes calldata data) external returns (uint32);

    /**
     * @dev Consume a scheduled operation targeting the caller. If such an operation exists, mark it as consumed
     * (emit an {OperationExecuted} event and clean the state). Otherwise, throw an error.
     *
     * This is useful for contract that want to enforce that calls targeting them were scheduled on the manager,
     * with all the verifications that it implies.
     *
     * Emit a {OperationExecuted} event.
     */
    function consumeScheduledOp(address caller, bytes calldata data) external;

    /**
     * @dev Hashing function for delayed operations.
     */
    function hashOperation(address caller, address target, bytes calldata data) external view returns (bytes32);

    /**
     * @dev Changes the authority of a target managed by this manager instance.
     *
     * Requirements:
     *
     * - the caller must be a global admin
     */
    function updateAuthority(address target, address newAuthority) external;
}

lib/openzeppelin-contracts/contracts/access/manager/IAuthority.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/manager/IAuthority.sol)

pragma solidity >=0.4.16;

/**
 * @dev Standard interface for permissioning originally defined in Dappsys.
 */
interface IAuthority {
    /**
     * @dev Returns true if the caller can invoke on a target the function identified by a function selector.
     */
    function canCall(address caller, address target, bytes4 selector) external view returns (bool allowed);
}

lib/openzeppelin-contracts/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @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 Context {
    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/contracts/utils/Panic.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}

lib/openzeppelin-contracts/contracts/utils/math/Math.sol

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

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

src/nav/interfaces/INAVDataProvider.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;

/**
 * @title NAV Data Provider Interface
 * @notice Minimal read surface for a NAV value and its source-data timestamp.
 */
interface INAVDataProvider {
    /**
     * @notice Return the current NAV and the time its source data was observed.
     * @return nav The latest NAV value with 18 decimal places.
     * @return timestamp The source observation time in Unix seconds. An intermediary must preserve
     *         this value rather than replace it with its own acceptance time.
     */
    function getCurrentNAV() external view returns (uint256 nav, uint256 timestamp);
}

src/nav/interfaces/INAVOracle.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;

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

/// @notice How an accepted NAV round was produced. Emitted with every round for monitoring/audit.
enum UpdateKind {
    Bootstrap, // initial seed recorded by the NAVOracle constructor
    Report, // automated up-or-flat write submitted through an authorized provider
    Force, // authorized manual up-or-flat write for outage or recovery use
    Markdown // delayed write-down; the only NAVOracle path that can decrease NAV
}

/// @notice Outcome of a {INAVOracle.submitReport} call.
/// @dev NAVOracle returns a status for accepted reports and terminal no-write outcomes; future-dated
///      observations and value-rail violations revert. Report providers are expected to treat a
///      returned status as transport success, but that mapping is provider behavior.
enum SubmitStatus {
    Accepted,
    IgnoredInProtection,
    DiscardedNonMonotonic,
    DiscardedStale
}

// ----- Shared events (file-level so NAVOracle and its report providers use one set of
//       declarations without inheritance) -----

/// @notice A new NAV round was accepted (any path — see kind).
event NAVUpdated(
    uint80 indexed roundId, uint256 nav, uint256 observationTimestamp, UpdateKind kind
);
/// @notice Chainlink V2 event signatures emitted by NAVOracle when it records a core round.
/// @dev `AnswerUpdated.current` is the raw 18-decimal core NAV, and the log emitter is NAVOracle.
///      It is not a scaled feed answer: for example, an 8-decimal NAVFeed returns
///      `floor(current / 1e10)` as `latestRoundData().answer`, while an 8-decimal NAVFeedProxy
///      returns that value from both `latestAnswer()` and `latestRoundData().answer`.
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
/// @notice A provider report arrived during Protection Mode and was ignored. The returned status
///         can be mapped to transport acknowledgement by the provider.
event ReportIgnoredInProtection(bytes32 indexed feedId, uint256 nav, uint256 observationTimestamp);
/// @notice A non-monotonic or stale provider observation was discarded.
/// @dev NAVOracle returns a discard status; transport retry behavior belongs to the provider.
event ReportDiscarded(
    bytes32 indexed feedId, uint256 nav, uint256 observationTimestamp, bytes4 reason
);
/// @notice An accepted provider report was written.
event ReportAccepted(
    bytes32 indexed feedId, uint256 nav, uint256 observationTimestamp, uint256 deviationBps
);
/// @notice Protection Mode entered (`by` is the enterer; every entry consumes the one-shot arming).
event ProtectionModeEntered(address indexed by, uint256 indexed episodeId, string reason);
/// @notice Protection Mode exited by an authorized caller.
event ProtectionModeExited(address indexed by);
/// @notice Protection entry was re-armed by an authorized caller.
event ProtectionEntryRearmed(address indexed by);
/// @notice A timelocked markdown executed: NAV decreased from previousNav to newNav.
event MarkdownApplied(uint80 indexed roundId, uint256 previousNav, uint256 newNav, string reason);
/// @notice Authorized manual up-or-flat write.
event NAVForceUpdated(address indexed by, uint256 nav, uint256 observationTimestamp, string reason);
/// @notice Constructor seed recorded as round 1 (no sink push).
event Bootstrapped(address indexed deployer, uint256 nav, uint256 dataTimestamp);

// Configuration events.
event NormalBandUpdated(uint256 previous, uint256 current);
event ForceBandUpdated(uint256 previous, uint256 current);
event MaxNAVUpdated(uint256 previous, uint256 current);

// ----- Shared errors (file-level for the same reason) -----

error ZeroAddress();
error ZeroFeedId();
error InvalidBounds();
error InvalidBand();
error InvalidVelocity();
error InvalidStaleness();
error NoData(uint80 roundId);
/// @dev Used as the {ReportDiscarded} reason selector for a non-monotonic observation; the
///      submission returns a discard status instead of reverting with this error.
error NonMonotonicObservation(uint256 observationTimestamp, uint256 lastObservationTs);
error ZeroObservationTimestamp();
error FutureObservation(uint256 observationTimestamp, uint256 blockTimestamp);
error StaleObservation(uint256 observationTimestamp);
error OutOfBounds(uint256 navValue);
error DeviationExceeded(uint256 navValue, uint256 currentNav, uint256 deviationBps);
error VelocityExceeded(uint256 navValue, uint256 moveWad, uint256 budgetWad);
error NAVMustNotDecrease(uint256 navValue, uint256 currentNav);
error ProtectionModeActive();
error ProtectionModeNotActive();
error ProtectionEntryNotArmed();
error MarkdownMustDecrease(uint256 navValue, uint256 currentNav);
error MarkdownBelowFloor(uint256 navValue, uint256 floor);
error MarkdownEpisodeMismatch(uint256 providedEpisode, uint256 currentEpisode);
error MarkdownTooFrequent(uint256 elapsed, uint256 required);
error MarkdownDelayNotElapsed(uint256 readyAt, uint256 nowTs);
error InvalidMarkdownDelay();
error ForceUpdateTooFrequent(uint256 elapsed, uint256 required);

/**
 * @title INAVOracle
 * @notice Protocol-facing surface implemented by {NAVOracle}. NAV uses 18-decimal fixed-point units
 *         on this surface; an integrator-facing feed may scale values to different decimals.
 *
 * @dev NAVOracle ignores automated reports and blocks force writes during Protection Mode, while
 *      delayed markdowns remain available. If no markdown executes, the latest round timestamp
 *      remains unchanged. AccessManager scheduling and any market action triggered by feed
 *      staleness are deployment and integrator policy rather than guarantees of this interface.
 */
interface INAVOracle is INAVDataProvider {
    /// @notice Number of decimals used by the protocol NAV surface.
    /// @dev NAVOracle returns 18. The distinct name avoids confusing protocol NAV decimals with an
    ///      AggregatorV3 feed's `decimals()`.
    function navDecimals() external pure returns (uint8);

    /// @notice Latest accepted round id (at least 1 because the constructor records the seed).
    function latestRound() external view returns (uint80);

    /// @notice Return a stored round. NAVOracle reverts {NoData} for a nonexistent round id.
    function getRound(uint80 roundId) external view returns (uint256 answer, uint256 updatedAt);

    /// @notice Whether Protection Mode is active.
    /// @dev NAVOracle ignores reports and blocks force writes while active; markdowns remain
    ///      available subject to their episode and timing gates.
    function protectionMode() external view returns (bool);

    /// @notice Monotonically increasing protection episode id used to bind NAVOracle markdowns.
    function protectionEpisodeId() external view returns (uint256);

    /// @notice Source-data timestamp associated with the current NAV value.
    /// @dev Bootstrap and reports preserve their source observation time; force writes and
    ///      markdowns use their execution block time. This is distinct from a round's `updatedAt`,
    ///      which records when this oracle accepted the round. It can move backward when a report
    ///      observed shortly before a force write is accepted afterward.
    function currentDataTimestamp() external view returns (uint256);

    /// @notice Timestamp used only for automated-report ordering and replay protection.
    /// @dev NAVOracle initializes it from the constructor seed's source-data timestamp. Accepted
    ///      reports and markdowns advance it; force writes do not. It is not necessarily the
    ///      timestamp associated with the current NAV value; use {currentDataTimestamp} for that.
    function lastObservationTs() external view returns (uint256);

    /// @notice The feed identifier this oracle serves (report providers bind against it).
    function feedId() external view returns (bytes32);

    /// @notice Submit a NAV observation to the implementing oracle.
    /// @dev NAVOracle restricts this call through its authority and enforces its value and ordering
    ///      rails. Transport authentication, decoding, and chain/feed binding remain provider
    ///      responsibilities; provider authorization is deployment wiring.
    /// @param navValue NAV in 18-decimal fixed-point units.
    /// @param observationTimestamp Observation time in Unix seconds.
    /// @return status Accepted or terminal no-write outcome.
    function submitReport(uint256 navValue, uint256 observationTimestamp)
        external
        returns (SubmitStatus);
}

src/nav/interfaces/INAVReceiver.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;

/**
 * @title NAV Receiver Interface
 * @notice Interface for downstream contracts that receive NAV updates from the oracle fan-out.
 */
interface INAVReceiver {
    /**
     * @notice Update the receiver's share price from a NAV value.
     * @param nav The NAV value with 18 decimal places.
     * @dev A receiver revert is isolated and reported by the oracle fan-out. The oracle write can
     *      still revert if the transaction lacks enough gas to reserve the receiver's call budget.
     */
    function setSharePrice(uint256 nav) external;
}

src/nav/interfaces/NAVSinkTypes.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;

// Shared sink events/errors and the legacy-consumer write surface used by NAVPushSinks and
// LegacyConsumerSinkAdapter. Sink callbacks use INAVReceiver. Registration and caller permissions
// are implementation and deployment concerns; local wiring checks live in
// script/VerifyAccessManagerWiring.s.sol.

/// @notice Minimal legacy-consumer write surface used by LegacyConsumerSinkAdapter.
/// @dev Authorization and legacy write rails are enforced by the deployed legacy consumer.
interface ILegacyNAVConsumer {
    function forceNAVUpdate(uint256 navValue, string calldata reason) external;
}

event SinkAdded(address indexed target);
event SinkRemoved(address indexed target);
/// @notice A sink call failed or exhausted its gas cap; fan-out continues to the next sink.
event SinkPushFailed(address indexed target, uint256 nav);

error SinkZeroAddress();
error SinkAlreadyRegistered(address target);
error SinkNotFound(address target);
error SinkNotAContract(address target);
error TooManySinks();
error InsufficientGasForSinkPush(address target);
/// @notice An explicit governance synchronization attempt failed to update the target sink.
error SinkSyncFailed(address target, uint256 nav);

src/nav/sinks/NAVPushSinks.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;

import {AccessManaged} from "@openzeppelin/contracts/access/manager/AccessManaged.sol";
import {INAVReceiver} from "../interfaces/INAVReceiver.sol";
// solhint-disable-next-line no-global-import — pulls in the sink events/errors.
import "../interfaces/NAVSinkTypes.sol";

/**
 * @title NAVPushSinks
 * @notice Access-managed registry and fan-out for downstream {INAVReceiver} sinks. NAVOracle pushes
 *         report, force-update, and markdown rounds; the constructor seed is not fanned out. Compatible
 *         receivers register directly, while targets with another write interface use an adapter.
 * @dev Each target's execution is gas-capped and return data is not copied. An ordinary target
 *      failure is reported without stopping fan-out. The write still reverts if it cannot reserve
 *      a target's full gas budget.
 */
abstract contract NAVPushSinks is AccessManaged {
    /// @notice Gas requested for target execution in each sink call.
    /// @dev Callers must also provision transaction gas for every registered sink and fan-out
    ///      overhead. Re-measure when sinks change.
    uint256 public constant SINK_GAS_LIMIT = 500_000;
    /// @notice Cap on registered sinks; bounds the number of external calls in each fan-out.
    uint256 public constant MAX_SINKS = 8;

    address[] private _sinks;

    /// @notice The registered downstream sinks, in push order.
    function sinks() external view returns (address[] memory) {
        return _sinks;
    }

    /// @notice Register a sink. Production AccessManager wiring should restrict this selector to
    ///         governance-authorized callers.
    function addSink(address target) external restricted {
        if (target == address(0)) revert SinkZeroAddress();
        // A codeless target would make every low-level push a silent success — fail at registration.
        if (target.code.length == 0) revert SinkNotAContract(target);
        uint256 n = _sinks.length;
        if (n >= MAX_SINKS) revert TooManySinks();
        for (uint256 i; i < n; ++i) {
            if (_sinks[i] == target) revert SinkAlreadyRegistered(target);
        }
        _sinks.push(target);
        emit SinkAdded(target);
    }

    /// @notice Deregister a sink (swap-and-pop; push order of the remaining sinks may change).
    function removeSink(address target) external restricted {
        uint256 n = _sinks.length;
        for (uint256 i; i < n; ++i) {
            if (_sinks[i] == target) {
                _sinks[i] = _sinks[n - 1];
                _sinks.pop();
                emit SinkRemoved(target);
                return;
            }
        }
        revert SinkNotFound(target);
    }

    /// @dev Whether `target` is currently registered.
    function _hasSink(address target) internal view returns (bool) {
        uint256 n = _sinks.length;
        for (uint256 i; i < n; ++i) {
            if (_sinks[i] == target) return true;
        }
        return false;
    }

    /// @dev Gas-capped push to a single sink (shared by the fan-out and {syncSink}).
    function _pushOne(address target, uint256 nav) internal returns (bool ok) {
        if (gasleft() < SINK_GAS_LIMIT + SINK_GAS_LIMIT / 63 + 5_000) {
            revert InsufficientGasForSinkPush(target);
        }
        bytes memory data = abi.encodeCall(INAVReceiver.setSharePrice, (nav));
        uint256 gasLimit = SINK_GAS_LIMIT;
        // Request zero output bytes so a sink cannot impose caller-side return-data copy costs.
        assembly ("memory-safe") {
            ok := call(gasLimit, target, 0, add(data, 0x20), mload(data), 0, 0)
        }
        if (!ok) emit SinkPushFailed(target, nav);
    }

    /// @dev Attempt to push an accepted NAV to every sink. A target failure emits {SinkPushFailed} and
    ///      iteration continues. Insufficient gas to reserve a target's full budget reverts the
    ///      write.
    function _pushSinks(uint256 nav) internal {
        uint256 n = _sinks.length;
        // EIP-150 can reduce forwarded gas to 63/64 of the caller's remaining gas. Before each call,
        // _pushOne requires enough gas to forward the full target budget. An underfunded iteration
        // reverts rather than committing without attempting that sink. The check is per iteration
        // because preceding sinks may consume different amounts.
        for (uint256 i; i < n; ++i) {
            _pushOne(_sinks[i], nav);
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 500,
    "enabled": true
  },
  "evmVersion": "shanghai",
  "remappings": [
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/[email protected]/=lib/openzeppelin-contracts/contracts/",
    "forge-std/=lib/forge-std/src/",
    "@chainlink/local/=lib/chainlink-local/",
    "@chainlink/contracts-ccip/contracts/=lib/chainlink-local/lib/chainlink-ccip/chains/evm/contracts/",
    "@chainlink/contracts-ccip/interfaces/=lib/chainlink-local/lib/chainlink-ccip/chains/evm/contracts/interfaces/",
    "@chainlink/contracts-ccip/libraries/=lib/chainlink-local/lib/chainlink-ccip/chains/evm/contracts/libraries/",
    "@chainlink/contracts-ccip/applications/=lib/chainlink-local/lib/chainlink-ccip/chains/evm/contracts/applications/",
    "solady/=lib/solady/src/",
    "@chainlink/=lib/chainlink/",
    "@openzeppelin/foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
    "openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
    "@openzeppelin/[email protected]/=lib/chainlink-local/src/vendor/openzeppelin-solidity/v4.7.3/contracts/",
    "@openzeppelin/[email protected]/=lib/chainlink-local/src/vendor/openzeppelin-solidity/v4.8.3/contracts/",
    "chainlink-ccip/=lib/chainlink-local/lib/chainlink-ccip/chains/evm/contracts/vendor/optimism/interop-lib/v0/src/",
    "chainlink-evm/=lib/chainlink-local/lib/chainlink-evm/",
    "chainlink-local/=lib/chainlink-local/src/",
    "chainlink/=lib/chainlink/",
    "ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "morpho-blue/=lib/morpho-blue/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "pendle-core-v2-public/=lib/pendle-core-v2-public/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.