Skip to content
Verified contractExactUNLICENSED

NavOracleAutomation

Address0xf30c1d76eb152db8f29916a264d87a4977f4a16e
Balance

0 ETH

 

Transactions

10

 

Compiler

solc 0.8.30

 

Same code

5 more contracts

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,948,440
Creation transaction
0x69145d07a5…2a26062045

contracts/automation/NavOracleAutomation.sol

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

import {AutomationCompatibleInterface} from "@chainlink/contracts/src/v0.8/automation/interfaces/AutomationCompatibleInterface.sol";
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";
import {AccessManaged} from "@openzeppelin/contracts/access/manager/AccessManaged.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {ILossManager} from "../interfaces/ILossManager.sol";
import {IMZUSD} from "../interfaces/IMZUSD.sol";
import {ITranche} from "../interfaces/ITranche.sol";
import {IVault} from "../interfaces/IVault.sol";
import {IPauseManager} from "../pause/IPauseManager.sol";
import {PauseCategory} from "../pause/PauseCategory.sol";

/// @title NAV oracle automation
/// @notice Stores oracle NAV snapshots with a veto window, then applies yield or loss via Automation.
/// @dev submitNav is AccessManaged; map it to ORACLE_ROLE in AccessManager, and grant this contract
///      a role that can call IssuanceVault.distributeYield and LossManager.applyLoss. NAV is USDC (6d).
/// @dev Trust model: submitted NAV is trusted oracle input. This contract does not validate NAV truthfulness,
///      it only enforces role-gated submission and optional veto delay before applying protocol accounting.
/// @dev The oracle uses a multi-package oracle solution by Redstone to retrieve NAV and Total Supply simultaoneusly.
/** @dev Description of the oracle solution:
 * Related RedStone feeds can be bundled into a single multi-point package and are then treated as one atomic update unit.
 *
 * Mechanism:
 * - On the node side, prices for both tokens are fetched separately.
 * - They are then combined into a single multi-point package signed once as one payload.
 * - Both the individual feeds and the combined package are broadcast to the Data Distribution Layer.
 * - On the relayer side, an additional guard ensures that feeds belonging to the same package cannot be updated independently on-chain.
 *
 * Guarantee:
 * - If two feeds are packaged together, either both are updated or neither is.
 * - If any token is missing from the multi-point package for any reason, the relayer skips the update for all feeds in that package.
 */
contract NavOracleAutomation is AutomationCompatibleInterface, AccessManaged {
    uint256 public constant SCALE = 1e12; // MZUSD (18d) -> USDC (6d)
    uint256 public constant ORACLE_SCALE = 1e2; // oracle answers (8d) -> USDC (6d)
    uint256 public constant MAX_VETO_PERIOD = 5 days;
    uint32 public constant DEFAULT_MAX_ANSWER_STALENESS = 30 minutes;
    address private constant VIRTUAL_SHARES_RECEIVER = 0x000000000000000000000000000000000000dEaD;

    IERC20 public immutable mzusd;
    address public immutable vault;
    address public immutable lossManager;
    IPauseManager public immutable pauseManager;
    AggregatorV3Interface public navOracle;
    AggregatorV3Interface public totalSupplyOracle;

    // Packed storage (31 bytes → 1 slot):
    // pendingDeltaUSDC (16) + pendingReadyAt (6) + pendingIsYield (1)
    // + vetoPeriod (4) + maxAnswerStaleness (4)
    // uint128 comfortably covers practical USDC (6d) deltas with wide headroom.
    uint128 public pendingDeltaUSDC;
    // uint48 timestamp is ample for ~8.9 million years; fits in one slot with surrounding fields.
    uint48 public pendingReadyAt;
    // Direction is stored separately to avoid signed-int casts/abs math during upkeep execution.
    bool public pendingIsYield;
    uint32 public vetoPeriod;
    uint32 public maxAnswerStaleness;

    event NavSubmitted(
        uint256 navUSDC,
        uint256 totalSupplyMZ,
        bool isYield,
        uint256 deltaUSDC,
        uint256 submittedAt,
        uint256 readyAt
    );
    event NavRejected(bool isYield, uint256 deltaUSDC, uint256 readyAt);
    event NavApplied(bool isYield, uint256 deltaUSDC, uint256 readyAt);
    event VetoPeriodUpdated(uint256 newPeriod);
    event OraclesUpdated(address indexed navOracle, address indexed totalSupplyOracle);
    event MaxAnswerStalenessUpdated(uint256 newMaxAnswerStaleness);

    error PendingNavExists();
    error NoPendingNav();
    error NotReady(uint256 readyAt);
    error InvalidVetoPeriod();
    error InvalidAnswerStaleness();
    error InvalidOracleAnswer(int256 answer);
    error InvalidOracleTimestamp(address oracle, uint256 updatedAt);
    error StaleOracleAnswer(
        address oracle,
        uint256 updatedAt,
        uint256 currentTimestamp,
        uint256 maxAnswerStaleness
    );
    error OraclesNotInSync();
    error ValueTooLarge();
    error ZeroAddress();
    error SameValue();

    /// @notice Wire NAV oracle automation to the LossManager and set the initial veto period.
    /// @param lossManager_ LossManager address; its MZUSD/vault/authority references are inherited.
    /// @param vetoPeriod_ Initial veto period in seconds applied to pending NAV submissions.
    constructor(
        address lossManager_,
        uint256 vetoPeriod_
    ) AccessManaged(_resolveAuthority(lossManager_)) {
        ILossManager manager = ILossManager(lossManager_);
        address vault_ = manager.vault();
        address mzusd_ = manager.mzusd();

        address pauseManager_ = IMZUSD(mzusd_).pauseManager();
        if (pauseManager_ == address(0)) revert ZeroAddress();

        mzusd = IERC20(mzusd_);
        vault = vault_;
        lossManager = lossManager_;
        pauseManager = IPauseManager(pauseManager_);
        _setVetoPeriod(vetoPeriod_);
        _setMaxAnswerStaleness(DEFAULT_MAX_ANSWER_STALENESS);
    }

    function _resolveAuthority(address lossManager_) private view returns (address accessManager) {
        address mzusd_ = ILossManager(lossManager_).mzusd();
        accessManager = IMZUSD(mzusd_).authority();
        if (accessManager == address(0)) revert ZeroAddress();
    }

    /// @notice Submit NAV and total supply snapshots from oracle feeds.
    /// @dev Reverts if a pending NAV exists. If vetoPeriod is 0, applies immediately.
    function submitNav() external restricted {
        if (hasPendingNav()) revert PendingNavExists();

        (uint256 navUSDC, uint256 totalSupplyMZ) = _readFreshAnswer(navOracle, totalSupplyOracle);

        (bool isYield, uint256 deltaUSDC) = _deltaUSDC(navUSDC, totalSupplyMZ);

        uint48 submittedAt = uint48(block.timestamp);
        uint256 readyAt = uint256(submittedAt) + uint256(vetoPeriod);

        if (deltaUSDC > type(uint128).max) revert ValueTooLarge();
        pendingDeltaUSDC = uint128(deltaUSDC);
        // Snapshot readiness for this pending NAV; changing vetoPeriod later
        // does not shift already submitted snapshots.
        pendingReadyAt = uint48(readyAt);
        pendingIsYield = isYield;

        emit NavSubmitted(navUSDC, totalSupplyMZ, isYield, deltaUSDC, submittedAt, readyAt);

        if (vetoPeriod == 0) {
            _applyPending();
        }
    }

    /// @notice Rejects the pending NAV snapshot during the veto window or before NAV is applied.
    function rejectPendingNav() external restricted {
        if (!hasPendingNav()) revert NoPendingNav();
        emit NavRejected(pendingIsYield, pendingDeltaUSDC, pendingReadyAt);
        _clearPending();
    }

    /// @notice Update the veto period for future submissions.
    /// @param newPeriod New veto period in seconds.
    function setVetoPeriod(uint256 newPeriod) external restricted {
        if (uint256(vetoPeriod) == newPeriod) revert SameValue();
        _setVetoPeriod(newPeriod);
        emit VetoPeriodUpdated(newPeriod);
    }

    /// @notice Update NAV and total supply oracle data feed addresses.
    /// @param newNavOracle Address of AggregatorV3-compatible NAV oracle.
    /// @param newTotalSupplyOracle Address of AggregatorV3-compatible total supply oracle.
    function setOracles(address newNavOracle, address newTotalSupplyOracle) external restricted {
        if (newNavOracle == address(0)) revert ZeroAddress();
        if (newTotalSupplyOracle == address(0)) revert ZeroAddress();
        navOracle = AggregatorV3Interface(newNavOracle);
        totalSupplyOracle = AggregatorV3Interface(newTotalSupplyOracle);
        emit OraclesUpdated(newNavOracle, newTotalSupplyOracle);
    }

    /// @notice Set maximum accepted oracle answer age.
    /// @param newMaxAnswerStaleness Maximum staleness in seconds.
    function setMaxAnswerStaleness(uint32 newMaxAnswerStaleness) external restricted {
        if (maxAnswerStaleness == newMaxAnswerStaleness) revert SameValue();
        _setMaxAnswerStaleness(newMaxAnswerStaleness);
        emit MaxAnswerStalenessUpdated(newMaxAnswerStaleness);
    }

    /// @notice Chainlink Automation check: pending NAV exists, veto period elapsed,
    ///         and downstream calls will not revert.
    /// @param checkData Unused; kept only for Chainlink Automation compatibility.
    /// @return upkeepNeeded True when a pending NAV is ready and can be applied without reverting.
    /// @return performData Empty; action is derived from on-chain state in performUpkeep.
    function checkUpkeep(
        bytes calldata checkData
    ) external view returns (bool upkeepNeeded, bytes memory performData) {
        checkData;
        if (!hasPendingNav()) return (false, "");
        if (block.timestamp < pendingReadyAt) return (false, "");

        // Both distributeYield and applyLoss advance the epoch, which reverts if
        // the current epoch has not fully elapsed yet.
        IVault v = IVault(vault);
        if (block.timestamp < v.epochStart() + v.epochDuration()) return (false, "");

        // Both paths touch the vault (distributeYield directly, applyLoss via advanceEpoch),
        // so a PROTOCOL pause on the vault blocks either action.
        if (pauseManager.isPaused(vault, PauseCategory.PROTOCOL)) return (false, "");

        // Both paths also touch MZUSD under a PROTOCOL pause guard: distributeYield mints
        // MZUSD, while applyLoss burns it. A PROTOCOL pause on MZUSD blocks either action.
        if (pauseManager.isPaused(address(mzusd), PauseCategory.PROTOCOL)) return (false, "");

        uint256 deltaUSDC = pendingDeltaUSDC;
        if (pendingIsYield) {
            // Non-zero yield distribution transfers MZUSD from the vault to tranches.
            if (deltaUSDC != 0 && pauseManager.isPaused(address(mzusd), PauseCategory.TRANSFERS))
                return (false, "");

            // distributeYield reverts when no tranches are registered, and the allocation step
            // reverts with TVLZero when no tranche contributes eligible TVL. Mirror the same
            // skip filter that IssuanceVault._allocateYieldToTranches applies: a tranche must
            // be enabled, have at least one share held outside VIRTUAL_SHARES_RECEIVER, and not
            // be PROTOCOL-paused, otherwise its totalAssets are excluded from eligible TVL.
            uint256 trancheCount = v.tranchesLength();
            if (trancheCount == 0) return (false, "");
            (address[] memory order, , bool[] memory enabled) = v.getTranches(0, trancheCount);
            uint256 totalTvl;
            for (uint256 i; i < trancheCount; ++i) {
                address tr = order[i];
                if (
                    !enabled[i] ||
                    IERC20(tr).totalSupply() == IERC20(tr).balanceOf(VIRTUAL_SHARES_RECEIVER) ||
                    pauseManager.isPaused(tr, PauseCategory.PROTOCOL)
                ) continue;
                totalTvl += ITranche(tr).totalAssets();
            }
            if (totalTvl == 0) return (false, "");
        } else {
            // applyLoss checks PROTOCOL pause on the LossManager.
            if (pauseManager.isPaused(lossManager, PauseCategory.PROTOCOL)) return (false, "");
            // applyLoss reverts when the loss exceeds the per-tx cap.
            uint256 maxLoss = ILossManager(lossManager).maxLossPerTxUSDC();
            if (maxLoss != 0 && deltaUSDC > maxLoss) return (false, "");
            // applyLoss also rejects losses greater than current MZUSD supply scaled to USDC.
            if (deltaUSDC > mzusd.totalSupply() / SCALE) return (false, "");
        }

        return (true, "");
    }

    /// @notice Applies pending NAV after the veto period.
    /// @param performData Unused; kept only for Chainlink Automation compatibility.
    /// @dev Action is derived from on-chain state to avoid data manipulation via calldata.
    function performUpkeep(bytes calldata performData) external restricted {
        performData;
        if (!hasPendingNav()) revert NoPendingNav();
        uint256 readyAt = pendingReadyAt;
        if (block.timestamp < readyAt) revert NotReady(readyAt);
        _applyPending();
    }

    /// @notice Returns true when a NAV snapshot is currently pending.
    /// @return True if a pending NAV exists (pendingReadyAt != 0).
    /// @dev Kept as an explicit getter for external integrations.
    function hasPendingNav() public view returns (bool) {
        return pendingReadyAt != 0;
    }

    /// @dev External calls to IssuanceVault/LossManager; pending state is cleared first
    function _applyPending() internal {
        bool isYield = pendingIsYield;
        uint256 deltaUSDC = pendingDeltaUSDC;
        uint256 readyAt = pendingReadyAt;

        _clearPending();

        if (isYield) {
            IVault(vault).distributeYield(deltaUSDC);
        } else {
            ILossManager(lossManager).applyLoss(deltaUSDC);
        }

        emit NavApplied(isYield, deltaUSDC, readyAt);
    }

    /// @dev Both `nav` and `totalSupply` are oracle answers reported with 8 decimals in the
    ///      same USD-denominated unit, so the delta is taken in 8-decimal space and only then
    ///      scaled down to USDC (6 decimals). Rounding stays conservative: yield rounds down
    ///      (distribute no more than covered) and loss rounds up (never under-apply a loss).
    function _deltaUSDC(
        uint256 nav,
        uint256 totalSupply
    ) internal pure returns (bool isYield, uint256 deltaUSDC) {
        if (nav >= totalSupply) {
            isYield = true;
            deltaUSDC = (nav - totalSupply) / ORACLE_SCALE;
        } else {
            isYield = false;
            deltaUSDC = (totalSupply - nav + ORACLE_SCALE - 1) / ORACLE_SCALE;
        }
    }

    function _clearPending() internal {
        pendingDeltaUSDC = 0;
        pendingReadyAt = 0;
        pendingIsYield = false;
    }

    function _setVetoPeriod(uint256 newPeriod) internal {
        if (newPeriod > MAX_VETO_PERIOD) revert InvalidVetoPeriod();
        _assertStalenessBound(maxAnswerStaleness, newPeriod);
        vetoPeriod = uint32(newPeriod);
    }

    function _setMaxAnswerStaleness(uint32 newMaxAnswerStaleness) internal {
        if (newMaxAnswerStaleness == 0) revert InvalidAnswerStaleness();
        _assertStalenessBound(newMaxAnswerStaleness, vetoPeriod);
        maxAnswerStaleness = newMaxAnswerStaleness;
    }

    /// @dev Enforces `staleness < max(veto, epochDuration)` so that same report
    ///      can't be applied in different epochs.
    function _assertStalenessBound(uint256 staleness, uint256 veto) internal view {
        uint256 epochDur = IVault(vault).epochDuration();
        uint256 bound = veto > epochDur ? veto : epochDur;
        if (staleness >= bound) revert InvalidAnswerStaleness();
    }

    function _readFreshAnswer(
        AggregatorV3Interface navOracle_,
        AggregatorV3Interface totalSupplyOracle_
    ) internal view returns (uint256 navUSDC, uint256 totalSupplyMZ) {
        if (address(navOracle_) == address(0)) revert ZeroAddress();
        if (address(totalSupplyOracle_) == address(0)) revert ZeroAddress();

        (, int256 navAnswer, , uint256 navUpdatedAt, ) = navOracle_.latestRoundData();
        if (navAnswer <= 0) revert InvalidOracleAnswer(navAnswer);
        if (navUpdatedAt == 0 || navUpdatedAt > block.timestamp) {
            revert InvalidOracleTimestamp(address(navOracle_), navUpdatedAt);
        }
        if (block.timestamp - navUpdatedAt > uint256(maxAnswerStaleness)) {
            revert StaleOracleAnswer(
                address(navOracle_),
                navUpdatedAt,
                block.timestamp,
                maxAnswerStaleness
            );
        }
        navUSDC = uint256(navAnswer);

        (, int256 supplyAnswer, , uint256 supplyUpdatedAt, ) = totalSupplyOracle_.latestRoundData();
        if (supplyAnswer <= 0) revert InvalidOracleAnswer(supplyAnswer);
        if (supplyUpdatedAt == 0 || supplyUpdatedAt > block.timestamp) {
            revert InvalidOracleTimestamp(address(totalSupplyOracle_), supplyUpdatedAt);
        }
        if (block.timestamp - supplyUpdatedAt > uint256(maxAnswerStaleness)) {
            revert StaleOracleAnswer(
                address(totalSupplyOracle_),
                supplyUpdatedAt,
                block.timestamp,
                maxAnswerStaleness
            );
        }
        // Both oracles should always be updated in the same transaction
        if (navUpdatedAt != supplyUpdatedAt) revert OraclesNotInSync();
        totalSupplyMZ = uint256(supplyAnswer);
    }
}

@chainlink/contracts/src/v0.8/automation/interfaces/AutomationCompatibleInterface.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

// solhint-disable-next-line interface-starts-with-i
interface AutomationCompatibleInterface {
  /**
   * @notice method that is simulated by the keepers to see if any work actually
   * needs to be performed. This method does does not actually need to be
   * executable, and since it is only ever simulated it can consume lots of gas.
   * @dev To ensure that it is never called, you may want to add the
   * cannotExecute modifier from KeeperBase to your implementation of this
   * method.
   * @param checkData specified in the upkeep registration so it is always the
   * same for a registered upkeep. This can easily be broken down into specific
   * arguments using `abi.decode`, so multiple upkeeps can be registered on the
   * same contract and easily differentiated by the contract.
   * @return upkeepNeeded boolean to indicate whether the keeper should call
   * performUpkeep or not.
   * @return performData bytes that the keeper should call performUpkeep with, if
   * upkeep is needed. If you would like to encode data to decode later, try
   * `abi.encode`.
   */
  function checkUpkeep(
    bytes calldata checkData
  ) external returns (bool upkeepNeeded, bytes memory performData);

  /**
   * @notice method that is actually executed by the keepers, via the registry.
   * The data returned by the checkUpkeep simulation will be passed into
   * this method to actually be executed.
   * @dev The input to this method should not be trusted, and the caller of the
   * method should not even be restricted to any single registry. Anyone should
   * be able call it, and the input should be validated, there is no guarantee
   * that the data passed in is the performData returned from checkUpkeep. This
   * could happen due to malicious keepers, racing keepers, or simply a state
   * change while the performUpkeep transaction is waiting for confirmation.
   * Always validate the data passed in.
   * @param performData is the data which was passed back from the checkData
   * simulation. If it is encoded, it can easily be decoded into other types by
   * calling `abi.decode`. This data should not be trusted, and should be
   * validated against the contract's current state.
   */
  function performUpkeep(
    bytes calldata performData
  ) external;
}

@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

// solhint-disable-next-line interface-starts-with-i
interface AggregatorV3Interface {
  function decimals() external view returns (uint8);

  function description() external view returns (string memory);

  function version() external view returns (uint256);

  function getRoundData(
    uint80 _roundId
  ) external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);

  function latestRoundData()
    external
    view
    returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}

@openzeppelin/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);
            }
        }
    }
}

@openzeppelin/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)))
            }
        }
    }
}

@openzeppelin/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);
}

@openzeppelin/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;
}

@openzeppelin/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);
}

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

@openzeppelin/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;
    }
}

contracts/interfaces/ILossManager.sol

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

interface ILossManager {
    function applyLoss(uint256 usdcLoss) external;
    function vault() external view returns (address);
    function mzusd() external view returns (address);
    function maxLossPerTxUSDC() external view returns (uint256);
}

contracts/interfaces/IMZUSD.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

interface IMZUSD is IERC20 {
    function mint(address to, uint256 amount) external;
    function burn(uint256 amount) external;
    function setVault(address vault) external;
    function usdc() external view returns (address);
    function vault() external view returns (address);
    function authority() external view returns (address);
    function pauseManager() external view returns (address);
    function decimals() external view returns (uint8);
}

contracts/interfaces/ITranche.sol

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

interface ITranche {
    function totalAssets() external view returns (uint256 assets);
    function notifyYield(uint256 amount) external;
    function burnMZUSD(uint256 amount) external;
    function vault() external view returns (address vaultAddress);
    function pauseManager() external view returns (address pauseManagerAddress);
    function umbrellaSharesByEpoch(uint256) external view returns (uint256 shares);
    function finalizedEpochs(
        uint256
    ) external view returns (uint256 totalShares, uint256 totalAssets, uint256 finalizationPrice);
    function finalizeEpoch(uint256) external;
}

contracts/interfaces/IVault.sol

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

interface IVault {
    function withdraw(address to, uint256 amountUSDC) external;
    function distributeYield(uint256 usdcReported) external;
    function advanceEpoch() external returns (uint256 newEpochId);
    function currentEpochId() external view returns (uint64 epochId);
    function epochStart() external view returns (uint48 start);
    function epochDuration() external view returns (uint64 duration);
    function lossManager() external view returns (address lossManager);
    function navOracle() external view returns (address navOracleAddress);
    function mzusd() external view returns (address mzusdAddress);
    function getTrancheOrder() external view returns (address[] memory order);
    function tranchesLength() external view returns (uint256 length);
    function getTranches(
        uint256 start,
        uint256 count
    )
        external
        view
        returns (
            address[] memory tranche,
            uint16[] memory riskPremiumBpsArr,
            bool[] memory enabled
        );
    function tranchePairedTo(address tranche) external view returns (address paired);
}

contracts/pause/IPauseManager.sol

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

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

interface IPauseManager {
    function isPaused(address target, PauseCategory category) external view returns (bool);

    function globalPaused(PauseCategory category) external view returns (bool);

    function contractPaused(address target, PauseCategory category) external view returns (bool);
}

contracts/pause/PauseCategory.sol

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

/// @notice Shared pause categories used across the protocol.
enum PauseCategory {
    DEPOSITS,
    WITHDRAWALS,
    TRANSFERS,
    ADMIN,
    PROTOCOL
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 200,
    "details": {
      "yulDetails": {
        "optimizerSteps": "u"
      }
    },
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.