Verified contractExactUNLICENSED
IssuanceVault
Address0xe8711a2905b50aa170768fe6eea24826ce201230
- Balance
0 ETH
- Transactions
1
- 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,432
- Creation transaction
- 0x8121ffc764…f5c8c54e3a
26 files
- contracts/IssuanceVault.solmain38.02 KB
- @openzeppelin/contracts-upgradeable/access/manager/AccessManagedUpgradeable.sol5.95 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol9.28 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol6.57 KB
- @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol1.19 KB
- @openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol4.51 KB
- @openzeppelin/contracts/access/manager/AuthorityUtils.sol1.38 KB
- @openzeppelin/contracts/access/manager/IAccessManaged.sol1.11 KB
- @openzeppelin/contracts/access/manager/IAccessManager.sol16.31 KB
- @openzeppelin/contracts/access/manager/IAuthority.sol483 B
- @openzeppelin/contracts/interfaces/IERC1967.sol637 B
- @openzeppelin/contracts/interfaces/draft-IERC1822.sol882 B
- @openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol6.24 KB
- @openzeppelin/contracts/proxy/beacon/IBeacon.sol473 B
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/utils/Address.sol6 KB
- @openzeppelin/contracts/utils/Errors.sol896 B
- @openzeppelin/contracts/utils/StorageSlot.sol4.18 KB
- contracts/interfaces/ILossManager.sol315 B
- contracts/interfaces/IMZUSD.sol595 B
- contracts/interfaces/INavOracleAutomation.sol267 B
- contracts/interfaces/IReservoir.sol368 B
- contracts/interfaces/ITranche.sol677 B
- contracts/pause/IPauseManager.sol416 B
- contracts/pause/PauseCategory.sol219 B
- contracts/pause/PauseManagedUpgradeable.sol2.06 KB
contracts/IssuanceVault.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/manager/AccessManagedUpgradeable.sol";
import "./pause/PauseManagedUpgradeable.sol";
import "./pause/PauseCategory.sol";
import {IPauseManager} from "./pause/IPauseManager.sol";
import "./interfaces/IMZUSD.sol";
import "./interfaces/IReservoir.sol";
import "./interfaces/ITranche.sol";
import "./interfaces/ILossManager.sol";
import "./interfaces/INavOracleAutomation.sol";
/// @title IssuanceVault
/// @notice Protocol treasury that mints MZUSD, manages yield distribution, buffers USDC for withdrawals/insurance,
/// and coordinates with the Reservoir where strategies live.
/// @dev This IssuanceVault is not an ERC4626 vault and does not mint user shares or represent deposits.
/// @dev Tranches are the ERC4626-like vaults for users.
// @dev This disables false positive by aderyn static analysis tool, it sees payable in upgradeToAndCall and raises an error about locking ether.
// aderyn-fp-next-line(contract-locks-ether)
contract IssuanceVault is
ReentrancyGuardUpgradeable,
UUPSUpgradeable,
AccessManagedUpgradeable,
PauseManagedUpgradeable
{
/// @notice Info for each registered tranche.
struct TrancheInfo {
address tranche;
uint16 riskPremiumBps; // 500 = 5%, 50 = 0.5%, 5 = 0.05%
bool enabled;
}
// aderyn-ignore-next-line(large-numeric-literal)
/// @notice Basis points denominator used across vault fee/yield parameters.
/// @dev Examples: 10_000 = 100%, 500 = 5%, 50 = 0.5%, 5 = 0.05%.
uint16 public constant BPS = 10_000;
uint16 public constant MAX_TOTAL_FEE_BPS = 5_000;
uint256 public constant SCALE = 1e12;
uint64 public constant MIN_EPOCH_DURATION_LIMIT = 1 hours;
uint64 public constant MAX_EPOCH_DURATION_LIMIT = 30 days;
uint16 public constant MAX_TRANCHES = 50;
address private constant VIRTUAL_SHARES_RECEIVER = 0x000000000000000000000000000000000000dEaD;
TrancheInfo[] public tranches;
// check if address is registered tranche
mapping(address => bool) public isTranche;
/// @notice Pairing lookup for loss allocation. If non-zero, tranche shares loss with the paired tranche.
mapping(address => address) public tranchePairedTo;
//IMMUTABLE
IERC20 public immutable usdc; // address of USDC token
IMZUSD public immutable mzusd; // address of MZUSD token, protocol stablecoin
IReservoir public immutable reservoir; // address of reservoir contract for idle USDC
address public performanceFeeReceiver; // receiver of performance fees
address public protocolFeeReceiver; // receiver of protocols fees
uint256 public idleBufferUSDC; // target idle USDC buffer in vault
// epochs + config
uint48 public epochStart; // start timestamp of current epoch
uint64 public epochDuration; // duration of each epoch in seconds
uint64 public currentEpochId; // current epoch ID for yield distribution
uint16 public hysteresisBps; // hysteresis band around idle buffer target (500 = 5%, 50 = 0.5%)
uint16 public performanceFeeBps; // portion of yield allocated to performance fees (500 = 5%, 50 = 0.5%)
uint16 public protocolFeeBps; // portion of yield allocated to protocol fees (500 = 5%, 50 = 0.5%)
uint16 public baseRewardBps; // portion of yield allocated to the base reward pool (500 = 5%, 50 = 0.5%)
address public lossManager; // canonical loss manager (set once)
address public navOracle; // canonical NAV automation address
uint64 public pendingEpochDuration; // queued duration to apply on next epoch
event FeesUpdated(
uint256 performanceBps,
address performanceReceiver,
uint256 protocolBps,
address protocolReceiver
);
event FeesPaid(uint256 performanceMZUSD, uint256 protocolMZUSD, uint256 epochId);
event Rebalanced(uint256 sent, uint256 pulled, uint256 idleAfter);
event YieldDistributed(uint256 usdcUsed, uint256 mintedMZUSD, uint256 epochId);
event TrancheRegistered(address tranche);
event BufferUpdated(uint256 buffer, uint256 hysteresisBps);
event BufferRebalanceSkipped();
event WithdrawnUSDCFromVault(address to, uint256 amount);
event LossManagerUpdated(address newLossManager);
event NavOracleUpdated(address newNavOracle);
/// @notice Emitted when the epoch is advanced.
/// @dev `startTs` is the block timestamp of the advance call (not previous `epochStart + epochDuration`).
event EpochAdvanced(uint256 indexed epochId, uint256 startTs);
event EpochDurationSet(uint256 epochDuration);
event EpochDurationQueued(uint256 epochDuration);
event TrancheConfigUpdated();
error AllocationMismatch(uint256 allocated, uint256 expected);
error ZeroAmount();
error NoTranchesAdded();
error TVLZero();
error TooBigBps();
error TrancheExists();
error ZeroAddress();
error EpochTooSoon();
error InvalidEpochDuration();
error TooManyTranches();
error SameValue();
error LossManagerAlreadySet();
error LossManagerNotSet();
error NotMZUSD();
error NotLossManager();
error NotNavOracle();
error InvalidMZUSDDecimals(uint8 actualDecimals);
error InvalidMZUSDUSDC(address actualUSDC);
error InvalidLossManagerVault(address actualVault);
error InvalidLossManagerMZUSD(address actualMZUSD);
error InvalidNavOracleVault(address actualVault);
error InvalidNavOracleLossManager(address actualLossManager);
error InvalidNavOracleMZUSD(address actualMZUSD);
error InvalidMZUSDAccessManager(address actualAccessManager);
error InvalidMZUSDPauseManager(address actualPauseManager);
error InvalidReservoirAccessManager(address actualAccessManager);
error InvalidReservoirPauseManager(address actualPauseManager);
error AddressHasNoCode(address candidate);
error InvalidReservoirUSDC(address actualUSDC);
error ReservoirEmpty();
error InvalidYieldDistribution();
error LengthMismatch();
error DuplicateTranche(address tranche);
error PairNotContiguous(uint256 index);
error TrancheNotRegistered(address tranche);
error PairedTrancheRiskPremiumMustBeZero();
error DisabledTrancheHasRiskPremium(address tranche);
error TrancheCountMismatch(uint256 provided, uint256 registered);
modifier onlyMZUSD() {
if (msg.sender != address(mzusd)) revert NotMZUSD();
_;
}
modifier onlyLossManager() {
if (msg.sender != lossManager) revert NotLossManager();
_;
}
modifier onlyNavOracle() {
if (msg.sender != navOracle) revert NotNavOracle();
_;
}
/// @notice Disable initializer on implementation contract and set immutable MZUSD, USDC, and Reservoir references.
/// @param _mzusd MZUSD token address; must be non-zero.
/// @param _reservoir ReservoirUSDC address; must be non-zero.
constructor(address _mzusd, address _reservoir) {
(IMZUSD token, address tokenUSDC) = _validateConstructorParams(_mzusd, _reservoir);
mzusd = token;
usdc = IERC20(tokenUSDC);
reservoir = IReservoir(_reservoir);
_disableInitializers();
}
/// @notice Initialize the IssuanceVault.
/// @param _performanceFeeBps Performance fee in bps (0 allowed; 500 = 5%, 50 = 0.5%, 5 = 0.05%).
/// @param _performanceFeeReceiver Recipient of performance fees.
/// @param _protocolFeeBps Protocol fee in bps (0 allowed; 500 = 5%, 50 = 0.5%, 5 = 0.05%).
/// @param _protocolFeeReceiver Recipient of protocol fees.
/// @param _epochDuration Epoch duration in seconds; must be within [MIN_EPOCH_DURATION, MAX_EPOCH_DURATION].
/// @dev _protocolFeeReceiver and _performanceFeeReceiver could be same addresses.
function initialize(
uint16 _performanceFeeBps,
address _performanceFeeReceiver,
uint16 _protocolFeeBps,
address _protocolFeeReceiver,
uint64 _epochDuration
) external initializer {
if (
_epochDuration < MIN_EPOCH_DURATION_LIMIT || _epochDuration > MAX_EPOCH_DURATION_LIMIT
) {
revert InvalidEpochDuration();
}
(address accessManager, address pauseManager_) = _resolveAndValidateCoreManagers();
__AccessManaged_init(accessManager);
__PauseManaged_init(pauseManager_);
__ReentrancyGuard_init();
_setFeeRates(_performanceFeeBps, _protocolFeeBps);
_setFeeReceivers(_performanceFeeReceiver, _protocolFeeReceiver);
// aderyn-ignore-next-line(large-numeric-literal)
idleBufferUSDC = 1_000_000 * 1e6;
hysteresisBps = 500;
currentEpochId = 1;
epochStart = uint48(block.timestamp);
epochDuration = _epochDuration;
}
/// @notice Withdraw USDC to a recipient (used for MZUSD redemptions).
/// @param to USDC recipient.
/// @param amount USDC amount (6 decimals).
/// @dev Callable only by the configured MZUSD contract.
function withdraw(
address to,
uint256 amount
) external onlyMZUSD whenNotPaused(PauseCategory.WITHDRAWALS) {
if (to == address(0)) revert ZeroAddress();
if (amount == 0) revert ZeroAmount();
uint256 idle = usdc.balanceOf(address(this));
if (idle < amount) {
reservoir.withdraw(amount - idle, address(this));
}
// USDC transfer will revert if balance is insufficient
usdc.transfer(to, amount);
emit WithdrawnUSDCFromVault(to, amount);
}
/// @notice Rebalance idle USDC between IssuanceVault and Reservoir.
function rebalance() external restricted whenNotPaused(PauseCategory.PROTOCOL) {
_rebalance();
}
/// @notice Distribute yield (reported in USDC) to tranches.
/// @param usdcReported USDC yield to distribute (6 decimals).
/// @dev Mints MZUSD 1:1 with reported USDC, advances epoch, mints fees,
/// and allocates by TVL and risk premium.
function distributeYield(
uint256 usdcReported
) external nonReentrant onlyNavOracle whenNotPaused(PauseCategory.PROTOCOL) {
if (tranches.length == 0) revert NoTranchesAdded();
// Always advance epoch on distribution call, even if yield is 0.
// This means yield can only be distributed once per epoch, and only at epoch start.
// Epochs are not necessarily contiguous; there can be an arbitrary pause between epochs
// until a distribution (or explicit advance) is triggered.
uint256 newEpochId = _advanceEpochAndValidate();
// NAV reporter is trusted: no extra balance checks are performed here.
// usdcReported is assumed to be correct for the accounting flows that follow.
if (usdcReported == 0) {
emit FeesPaid(0, 0, newEpochId);
emit YieldDistributed(0, 0, newEpochId);
return;
}
uint256 mintedGross = usdcReported * SCALE;
(uint256 allocatableMZUSD, uint256 perfFee, uint256 protFee) = _handleFees(mintedGross);
emit FeesPaid(perfFee, protFee, newEpochId);
if (allocatableMZUSD == 0) {
emit YieldDistributed(usdcReported, 0, newEpochId);
return;
}
// Allocation model: mint allocatable MZUSD to the IssuanceVault, then transfer to tranches.
// Dust is assigned to the last non-zero tranche, so the IssuanceVault should end with no MZUSD.
mzusd.mint(address(this), allocatableMZUSD);
uint256 actuallyAllocated = _allocateYieldToTranches(allocatableMZUSD);
emit YieldDistributed(usdcReported, actuallyAllocated, newEpochId);
}
//SETTERS
/// @notice Set LossManager address (one-time).
/// @param _lossManager LossManager proxy address. Must be non-zero, deployed, and wired to this vault and its MZUSD.
/// @dev Reverts if already set, if the address has no code, or if vault/MZUSD cross-references do not match.
function setLossManager(
address _lossManager
) external restricted whenNotPaused(PauseCategory.ADMIN) {
if (_lossManager == address(0)) revert ZeroAddress();
if (lossManager != address(0)) revert LossManagerAlreadySet();
if (_lossManager.code.length == 0) revert AddressHasNoCode(_lossManager);
address lmVault = ILossManager(_lossManager).vault();
if (lmVault != address(this)) revert InvalidLossManagerVault(lmVault);
address lmMZUSD = ILossManager(_lossManager).mzusd();
if (lmMZUSD != address(mzusd)) revert InvalidLossManagerMZUSD(lmMZUSD);
lossManager = _lossManager;
emit LossManagerUpdated(_lossManager);
}
/// @notice Update NAV oracle automation address.
/// @param _navOracle NavOracleAutomation address. Must be non-zero, deployed, and wired to this vault, its LossManager, and MZUSD.
/// @dev LossManager must be set before calling. Reverts if cross-references do not match.
function setNavOracle(
address _navOracle
) external restricted whenNotPaused(PauseCategory.ADMIN) {
if (_navOracle == address(0)) revert ZeroAddress();
if (navOracle == _navOracle) revert SameValue();
if (lossManager == address(0)) revert LossManagerNotSet();
if (_navOracle.code.length == 0) revert AddressHasNoCode(_navOracle);
INavOracleAutomation oracle = INavOracleAutomation(_navOracle);
address oracleVault = oracle.vault();
if (oracleVault != address(this)) revert InvalidNavOracleVault(oracleVault);
address oracleLossManager = oracle.lossManager();
if (oracleLossManager != lossManager) {
revert InvalidNavOracleLossManager(oracleLossManager);
}
address oracleMZUSD = oracle.mzusd();
if (oracleMZUSD != address(mzusd)) revert InvalidNavOracleMZUSD(oracleMZUSD);
navOracle = _navOracle;
emit NavOracleUpdated(_navOracle);
}
/// @notice Update fee rates (bps).
/// @param _performanceFeeBps Performance fee in bps (500 = 5%, 50 = 0.5%, 5 = 0.05%).
/// @param _protocolFeeBps Protocol fee in bps (500 = 5%, 50 = 0.5%, 5 = 0.05%).
/// @dev Sum of performanceFeeBps and protocolFeeBps must not exceed MAX_TOTAL_FEE_BPS.
/// @dev A non-zero fee requires a non-zero matching receiver.
function setFeeRates(
uint16 _performanceFeeBps,
uint16 _protocolFeeBps
) external restricted whenNotPaused(PauseCategory.ADMIN) {
if (_performanceFeeBps != 0 && performanceFeeReceiver == address(0)) {
revert ZeroAddress();
}
if (_protocolFeeBps != 0 && protocolFeeReceiver == address(0)) {
revert ZeroAddress();
}
_setFeeRates(_performanceFeeBps, _protocolFeeBps);
emit FeesUpdated(
performanceFeeBps,
performanceFeeReceiver,
protocolFeeBps,
protocolFeeReceiver
);
}
/// @notice Update fee receivers.
/// @param _performanceFeeReceiver Recipient of performance fees; must be non-zero.
/// @param _protocolFeeReceiver Recipient of protocol fees; must be non-zero. May equal _performanceFeeReceiver.
function setFeeReceivers(
address _performanceFeeReceiver,
address _protocolFeeReceiver
) external restricted whenNotPaused(PauseCategory.ADMIN) {
_setFeeReceivers(_performanceFeeReceiver, _protocolFeeReceiver);
emit FeesUpdated(
performanceFeeBps,
performanceFeeReceiver,
protocolFeeBps,
protocolFeeReceiver
);
}
/// @notice Register a new tranche.
/// @param _tranche Tranche contract address to register; must be non-zero and not already registered.
/// @dev Tranche is disabled by default as adding of new tranche requires to reset yield distribution via setTrancheConfig().
function registerTranche(
address _tranche
) external restricted whenNotPaused(PauseCategory.ADMIN) {
if (_tranche == address(0)) revert ZeroAddress();
if (isTranche[_tranche]) revert TrancheExists();
if (tranches.length >= MAX_TRANCHES) revert TooManyTranches();
tranches.push(TrancheInfo(_tranche, 0, false));
isTranche[_tranche] = true;
emit TrancheRegistered(_tranche);
}
/// @notice Configure tranche order, pairing, and yield distribution in one call.
/// @param _tranches Tranche info structs in desired burn/allocation order (must all be registered).
/// @param _isPairedWithNext Pair flags aligned with `_tranches` (contiguous true,true for pairs).
/// @param _baseRewardBps Base reward pool share in bps (500 = 5%, 50 = 0.5%, 5 = 0.05%).
/// @dev Enforces: all registered, no duplicates, pair contiguity, _baseRewardBps + sum(riskPremiums) == BPS.
/// @dev Each `_tranches[i].riskPremiumBps` uses the same scale (10_000 = 100%).
function setTrancheConfig(
TrancheInfo[] calldata _tranches,
bool[] calldata _isPairedWithNext,
uint16 _baseRewardBps
) external restricted whenNotPaused(PauseCategory.ADMIN) {
uint256 len = _tranches.length;
if (len == 0) revert NoTranchesAdded();
if (len != tranches.length) revert TrancheCountMismatch(len, tranches.length);
if (_isPairedWithNext.length != len) revert LengthMismatch();
// Validate registered, no duplicates, enabled↔premium consistency, and sum yield to BPS.
uint256 total = _baseRewardBps;
for (uint256 i; i < len; ++i) {
address tranche = _tranches[i].tranche;
if (!isTranche[tranche]) revert TrancheNotRegistered(tranche);
for (uint256 j; j < i; ++j) {
if (_tranches[j].tranche == tranche) revert DuplicateTranche(tranche);
}
if (!_tranches[i].enabled && _tranches[i].riskPremiumBps != 0) {
revert DisabledTrancheHasRiskPremium(tranche);
}
total += _tranches[i].riskPremiumBps;
}
if (total != BPS) revert InvalidYieldDistribution();
// Clear old pair mapping.
for (uint256 i; i < len; ++i) {
delete tranchePairedTo[tranches[i].tranche];
}
// Overwrite tranches array, validate pair contiguity and build pair mapping.
tranches = _tranches;
for (uint256 i; i < len; ) {
if (!_isPairedWithNext[i]) {
++i;
continue;
}
if (i + 1 >= len) revert PairNotContiguous(i);
if (!_isPairedWithNext[i + 1]) revert PairNotContiguous(i);
if (_tranches[i + 1].riskPremiumBps != 0) revert PairedTrancheRiskPremiumMustBeZero();
tranchePairedTo[_tranches[i].tranche] = _tranches[i + 1].tranche;
tranchePairedTo[_tranches[i + 1].tranche] = _tranches[i].tranche;
i += 2;
}
baseRewardBps = _baseRewardBps;
emit TrancheConfigUpdated();
}
/// @notice Update idle USDC buffer and hysteresis band.
/// @param target Target idle USDC buffer (6 decimals).
/// @param bandBps Hysteresis band in bps (500 = 5%, 50 = 0.5%, 5 = 0.05%).
function setBuffer(
uint256 target,
uint16 bandBps
) external restricted whenNotPaused(PauseCategory.ADMIN) {
if (bandBps > BPS) revert TooBigBps();
if (target == 0) revert ZeroAmount();
idleBufferUSDC = target;
hysteresisBps = bandBps;
emit BufferUpdated(target, bandBps);
uint256 idle = usdc.balanceOf(address(this));
(uint256 low, ) = _bufferBounds();
if (idle < low) {
uint256 available = usdc.balanceOf(address(reservoir));
if (available == 0) {
emit BufferRebalanceSkipped();
return;
}
}
_rebalance();
}
/// @notice Queue epoch duration update for next epoch.
/// @dev AccessManager should enforce an execution delay for this method.
/// @param _epochDuration New epoch duration in seconds.
function setEpochConfig(
uint64 _epochDuration
) external restricted whenNotPaused(PauseCategory.ADMIN) {
if (
_epochDuration < MIN_EPOCH_DURATION_LIMIT || _epochDuration > MAX_EPOCH_DURATION_LIMIT
) {
revert InvalidEpochDuration();
}
if (pendingEpochDuration == _epochDuration) revert SameValue();
pendingEpochDuration = _epochDuration;
emit EpochDurationQueued(_epochDuration);
}
/// @notice Advances the epoch if enough time has passed.
/// @dev Heartbeat for periods with zero yield, so other epoch-based flows can progress.
/// @return newEpochId The new epoch ID after advancement.
function advanceEpoch()
external
onlyLossManager
whenNotPaused(PauseCategory.PROTOCOL)
returns (uint256 newEpochId)
{
return _advanceEpochAndValidate();
}
//GETTERS
/// @notice Number of registered tranches.
/// @return length Count of registered tranches.
function tranchesLength() external view returns (uint256 length) {
length = tranches.length;
}
/// @notice Current idle USDC balance held by this vault.
/// @return idleUSDC USDC amount (6 decimals).
function currentIdleUSDC() external view returns (uint256 idleUSDC) {
idleUSDC = usdc.balanceOf(address(this));
}
/// @notice Get tranche info in paginated manner.
/// @param start The starting tranche index.
/// @param count The number of tranches to return.
/// @return tranche The tranche addresses.
/// @return riskPremiumBpsArr The tranche risk premium (bps).
/// @return enabled The tranche enabled flags.
function getTranches(
uint256 start,
uint256 count
)
external
view
returns (address[] memory tranche, uint16[] memory riskPremiumBpsArr, bool[] memory enabled)
{
uint256 len = tranches.length;
if (start >= len || count == 0) {
return (new address[](0), new uint16[](0), new bool[](0));
}
uint256 end = start + count;
if (end > len) {
end = len;
}
uint256 size = end - start;
tranche = new address[](size);
riskPremiumBpsArr = new uint16[](size);
enabled = new bool[](size);
for (uint256 i; i < size; ++i) {
TrancheInfo memory t = tranches[start + i];
tranche[i] = t.tranche;
riskPremiumBpsArr[i] = t.riskPremiumBps;
enabled[i] = t.enabled;
}
}
///@notice Get current epoch configuration.
///@return epochId Current epoch ID.
///@return start Current epoch start timestamp (set to the timestamp of the last epoch advance).
///@return duration Current epoch duration in seconds.
function getEpochConfig()
external
view
returns (uint64 epochId, uint48 start, uint64 duration)
{
return (currentEpochId, epochStart, epochDuration);
}
/// @notice Returns idle buffer configuration and computed hysteresis bounds.
/// @return buffer Target idle USDC buffer (6 decimals).
/// @return hysteresis Hysteresis band in bps (500 = 5%).
/// @return low Lower hysteresis bound in USDC (6 decimals); rebalance pulls from reservoir below this.
/// @return high Upper hysteresis bound in USDC (6 decimals); rebalance sends to reservoir above this.
function getBufferConfig()
external
view
returns (uint256 buffer, uint16 hysteresis, uint256 low, uint256 high)
{
(low, high) = _bufferBounds();
return (idleBufferUSDC, hysteresisBps, low, high);
}
/// @notice Returns ordered tranche addresses (same order as `tranches[]`).
/// @return order Array of tranche addresses in configured loss/allocation order.
function getTrancheOrder() external view returns (address[] memory order) {
uint256 len = tranches.length;
order = new address[](len);
for (uint256 i; i < len; ++i) {
order[i] = tranches[i].tranche;
}
}
/// @notice Returns current tranche order and pair flags.
/// @return order Array of tranche addresses in configured order.
/// @return isPairedWithNext Boolean flags; `true,true` at indices `i` and `i+1` indicates a pair.
/// @dev Pair is represented symmetrically as `true,true` at indices `i` and `i+1`.
function getTrancheOrderAndPairs()
external
view
returns (address[] memory order, bool[] memory isPairedWithNext)
{
uint256 len = tranches.length;
order = new address[](len);
isPairedWithNext = new bool[](len);
for (uint256 i; i < len; ++i) {
address tranche = tranches[i].tranche;
order[i] = tranche;
if (i + 1 < len && tranchePairedTo[tranche] == tranches[i + 1].tranche) {
isPairedWithNext[i] = true;
isPairedWithNext[i + 1] = true;
}
}
}
//INTERNAL HELPERS
/// @notice Validate constructor parameters.
/// @param _mzusd MZUSD token address.
/// @param _reservoir Reservoir contract address.
/// @return token Validated MZUSD token interface.
/// @return tokenUSDC MZUSD's USDC address.
function _validateConstructorParams(
address _mzusd,
address _reservoir
) internal view returns (IMZUSD token, address tokenUSDC) {
if (_mzusd == address(0) || _reservoir == address(0)) revert ZeroAddress();
token = IMZUSD(_mzusd);
uint8 decimals = token.decimals();
if (decimals != 18) revert InvalidMZUSDDecimals(decimals);
tokenUSDC = token.usdc();
if (tokenUSDC == address(0)) revert InvalidMZUSDUSDC(tokenUSDC);
address reservoirUSDC = IReservoir(_reservoir).usdc();
if (reservoirUSDC != tokenUSDC) revert InvalidReservoirUSDC(reservoirUSDC);
}
/// @notice Resolve and validate AccessManager and PauseManager from MZUSD/Reservoir.
/// @dev Enforces that MZUSD and Reservoir are wired to the same authority and pause manager.
function _resolveAndValidateCoreManagers()
internal
view
returns (address accessManager, address pauseManager_)
{
accessManager = mzusd.authority();
if (accessManager == address(0)) {
revert InvalidMZUSDAccessManager(accessManager);
}
pauseManager_ = mzusd.pauseManager();
if (pauseManager_ == address(0)) {
revert InvalidMZUSDPauseManager(pauseManager_);
}
address reservoirAccessManager = reservoir.authority();
if (reservoirAccessManager != accessManager) {
revert InvalidReservoirAccessManager(reservoirAccessManager);
}
address reservoirPauseManager = reservoir.pauseManager();
if (reservoirPauseManager != pauseManager_) {
revert InvalidReservoirPauseManager(reservoirPauseManager);
}
}
/// @notice Internal function to set fee rates.
/// @param _performanceFeeBps Performance fee in bps (500 = 5%, 50 = 0.5%, 5 = 0.05%).
/// @param _protocolFeeBps Protocol fee in bps (500 = 5%, 50 = 0.5%, 5 = 0.05%).
/// @dev Sum of _performanceFeeBps and _protocolFeeBps must not exceed MAX_TOTAL_FEE_BPS.
function _setFeeRates(uint16 _performanceFeeBps, uint16 _protocolFeeBps) internal {
if (_performanceFeeBps + _protocolFeeBps > MAX_TOTAL_FEE_BPS) revert TooBigBps();
performanceFeeBps = _performanceFeeBps;
protocolFeeBps = _protocolFeeBps;
}
/// @notice Internal function to set fee receivers.
/// @param _performanceFeeReceiver Recipient of performance fees.
/// @param _protocolFeeReceiver Recipient of protocol fees.
/// @dev _performanceFeeReceiver and _protocolFeeReceiver must be non-zero.
/// @dev _performanceFeeReceiver and _protocolFeeReceiver could be same addresses.
function _setFeeReceivers(
address _performanceFeeReceiver,
address _protocolFeeReceiver
) internal {
if (_performanceFeeReceiver == address(0) || _protocolFeeReceiver == address(0)) {
revert ZeroAddress();
}
performanceFeeReceiver = _performanceFeeReceiver;
protocolFeeReceiver = _protocolFeeReceiver;
}
/// @notice Advance epoch and validate that enough time has passed.
/// @dev Requires `block.timestamp >= epochStart + epochDuration`.
/// @dev New `epochStart` is anchored to `block.timestamp` at advance time.
/// If advancement is delayed, elapsed idle time is not backfilled into synthetic epochs.
/// @return newEpochId New epoch ID after advancement.
function _advanceEpochAndValidate() internal returns (uint256 newEpochId) {
uint48 ts = uint48(block.timestamp);
if (ts < epochStart + epochDuration) revert EpochTooSoon();
epochStart = ts;
newEpochId = ++currentEpochId;
emit EpochAdvanced(newEpochId, ts);
uint64 queuedDuration = pendingEpochDuration;
if (queuedDuration != 0) {
epochDuration = queuedDuration;
pendingEpochDuration = 0;
emit EpochDurationSet(queuedDuration);
}
}
/// @notice Mint fees in MZUSD based on the gross minted amount.
/// @param mintedGross Gross MZUSD minted for yield distribution (18 decimals).
/// @return mintedForAllocation MZUSD remaining for tranche allocation after fees.
/// @return performanceFeeMZUSD MZUSD minted as the performance fee.
/// @return protocolFeeMZUSD MZUSD minted as the protocol fee.
function _handleFees(
uint256 mintedGross
)
internal
returns (uint256 mintedForAllocation, uint256 performanceFeeMZUSD, uint256 protocolFeeMZUSD)
{
performanceFeeMZUSD = _mintFee(performanceFeeBps, performanceFeeReceiver, mintedGross);
protocolFeeMZUSD = _mintFee(protocolFeeBps, protocolFeeReceiver, mintedGross);
mintedForAllocation = mintedGross - performanceFeeMZUSD - protocolFeeMZUSD;
}
/// @notice Mint a fee in MZUSD.
/// @param bps Fee in basis points (500 = 5%, 50 = 0.5%, 5 = 0.05%).
/// @param receiver Recipient of the fee.
/// @param mintedGross Gross MZUSD minted for yield distribution (18 decimals).
/// @return feeAmount MZUSD minted as the fee.
function _mintFee(
uint16 bps,
address receiver,
uint256 mintedGross
) internal returns (uint256 feeAmount) {
if (bps == 0 || receiver == address(0)) {
return 0;
}
feeAmount = (mintedGross * bps) / BPS;
if (feeAmount == 0) {
return 0;
}
mzusd.mint(receiver, feeAmount);
}
/// @notice Allocate yield to tranches based on weights and TVL.
/// @param allocatableMZUSD MZUSD available for allocation (18 decimals).
/// @return actuallyAllocated MZUSD actually allocated to tranches.
/// @dev Tranches are expected to be ERC4626 vaults over MZUSD (18 decimals),
/// so totalAssets() is already in MZUSD units. If multi-asset tranches are
/// introduced later, normalize units before scoring.
/// @dev Paired tranches receive a combined base + risk premium share (using
/// the first tranche's riskPremiumBps), then split the total by TVL ratio.
function _allocateYieldToTranches(
uint256 allocatableMZUSD
) internal returns (uint256 actuallyAllocated) {
IMZUSD mzusdToken = mzusd;
uint256 trancheCount = tranches.length;
uint256 basePool = (allocatableMZUSD * baseRewardBps) / BPS;
uint256[] memory trancheTvls = new uint256[](trancheCount);
uint256 totalTvl;
uint256 lastNonZeroIndex;
IPauseManager pauseManagerCached = IPauseManager(pauseManager());
TrancheInfo memory t;
uint256 trancheTvl;
for (uint256 i; i < trancheCount; ++i) {
t = tranches[i];
trancheTvl = ITranche(t.tranche).totalAssets();
if (
!t.enabled ||
trancheTvl == 0 ||
IERC20(t.tranche).totalSupply() ==
IERC20(t.tranche).balanceOf(VIRTUAL_SHARES_RECEIVER) ||
pauseManagerCached.isPaused(t.tranche, PauseCategory.PROTOCOL)
) continue;
trancheTvls[i] = trancheTvl;
totalTvl += trancheTvl;
// Track the last tranche that actually participates in allocation.
// Dust will be assigned there to avoid leftover MZUSD on the IssuanceVault.
lastNonZeroIndex = i;
}
if (totalTvl == 0) revert TVLZero();
uint256 allocated;
for (uint256 i; i < trancheCount; ) {
t = tranches[i];
address pairedAddr = tranchePairedTo[t.tranche];
// ── Paired tranche handling ──────────────────────────────
if (
pairedAddr != address(0) &&
i + 1 < trancheCount &&
tranches[i + 1].tranche == pairedAddr
) {
uint256 tvl0 = trancheTvls[i];
uint256 tvl1 = trancheTvls[i + 1];
uint256 pairTvl = tvl0 + tvl1;
if (pairTvl == 0) {
i += 2;
continue;
}
uint256 pairTotal;
if (i == lastNonZeroIndex || i + 1 == lastNonZeroIndex) {
pairTotal = allocatableMZUSD - allocated;
} else {
uint256 pairBaseShare = (basePool * pairTvl) / totalTvl;
uint256 pairRiskPremium = (allocatableMZUSD * t.riskPremiumBps) / BPS;
pairTotal = pairBaseShare + pairRiskPremium;
}
uint256 share0;
uint256 share1;
if (tvl0 == 0) {
share1 = pairTotal;
} else if (tvl1 == 0) {
share0 = pairTotal;
} else {
share0 = (pairTotal * tvl0) / pairTvl;
share1 = pairTotal - share0;
}
if (share0 != 0) {
mzusdToken.transfer(t.tranche, share0);
ITranche(t.tranche).notifyYield(share0);
}
if (share1 != 0) {
mzusdToken.transfer(pairedAddr, share1);
ITranche(pairedAddr).notifyYield(share1);
}
allocated += share0 + share1;
i += 2;
continue;
}
// ── Solo tranche handling ────────────────────────────────
trancheTvl = trancheTvls[i];
if (trancheTvl == 0) {
++i;
continue;
}
uint256 totalShare;
if (i == lastNonZeroIndex) {
totalShare = allocatableMZUSD - allocated;
} else {
uint256 baseShare = (basePool * trancheTvl) / totalTvl;
uint256 riskPremiumShare = (allocatableMZUSD * t.riskPremiumBps) / BPS;
totalShare = baseShare + riskPremiumShare;
}
if (totalShare != 0) {
mzusdToken.transfer(t.tranche, totalShare);
ITranche(t.tranche).notifyYield(totalShare);
allocated += totalShare;
}
++i;
}
// Defensive check: allocation should consume the full allocatable amount.
// If this ever fails, it prevents silent leftover MZUSD on the IssuanceVault.
if (allocated != allocatableMZUSD) {
revert AllocationMismatch(allocated, allocatableMZUSD);
}
return allocatableMZUSD;
}
/// @notice Compute buffer bounds based on idle buffer and hysteresis.
function _bufferBounds() internal view returns (uint256 low, uint256 high) {
uint256 buffer = idleBufferUSDC;
uint16 bandBps = hysteresisBps;
low = (buffer * (BPS - bandBps)) / BPS;
high = (buffer * (BPS + bandBps)) / BPS;
}
/// @notice Rebalance idle USDC against the target buffer and hysteresis band.
/// @dev Sends excess to Reservoir or pulls when below the low bound.
/// @dev When there is no much money in Reservoir, it will pull whatever is available.
/// @dev If Reservoir is empty, it reverts.
function _rebalance() internal {
uint256 idle = usdc.balanceOf(address(this));
(uint256 low, uint256 high) = _bufferBounds();
uint256 sent;
uint256 pulled;
if (idle > high) {
sent = idle - idleBufferUSDC;
usdc.approve(address(reservoir), sent);
reservoir.deposit(sent);
} else if (idle < low) {
uint256 need = idleBufferUSDC - idle;
uint256 available = usdc.balanceOf(address(reservoir));
if (available == 0) revert ReservoirEmpty();
pulled = available < need ? available : need;
reservoir.withdraw(pulled, address(this));
}
emit Rebalanced(sent, pulled, usdc.balanceOf(address(this)));
}
/// @notice While restricted is applied to the internal _authorizeUpgrade function, AccessManager should be configured to restrict call to upgradeToAndCall function, as it's the public entry point.
// aderyn-fp-next-line(empty-block)
function _authorizeUpgrade(address newImpl) internal override restricted {}
}
@openzeppelin/contracts-upgradeable/access/manager/AccessManagedUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/manager/AccessManaged.sol)
pragma solidity ^0.8.20;
import {AuthorityUtils} from "@openzeppelin/contracts/access/manager/AuthorityUtils.sol";
import {IAccessManager} from "@openzeppelin/contracts/access/manager/IAccessManager.sol";
import {IAccessManaged} from "@openzeppelin/contracts/access/manager/IAccessManaged.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {Initializable} from "../../proxy/utils/Initializable.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 AccessManagedUpgradeable is Initializable, ContextUpgradeable, IAccessManaged {
/// @custom:storage-location erc7201:openzeppelin.storage.AccessManaged
struct AccessManagedStorage {
address _authority;
bool _consumingSchedule;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessManaged")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessManagedStorageLocation = 0xf3177357ab46d8af007ab3fdb9af81da189e1068fefdc0073dca88a2cab40a00;
function _getAccessManagedStorage() private pure returns (AccessManagedStorage storage $) {
assembly {
$.slot := AccessManagedStorageLocation
}
}
/**
* @dev Initializes the contract connected to an initial authority.
*/
function __AccessManaged_init(address initialAuthority) internal onlyInitializing {
__AccessManaged_init_unchained(initialAuthority);
}
function __AccessManaged_init_unchained(address initialAuthority) internal onlyInitializing {
_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) {
AccessManagedStorage storage $ = _getAccessManagedStorage();
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) {
AccessManagedStorage storage $ = _getAccessManagedStorage();
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 {
AccessManagedStorage storage $ = _getAccessManagedStorage();
$._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 {
AccessManagedStorage storage $ = _getAccessManagedStorage();
(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-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reinitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
*
* NOTE: Consider following the ERC-7201 formula to derive storage locations.
*/
function _initializableStorageSlot() internal pure virtual returns (bytes32) {
return INITIALIZABLE_STORAGE;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
bytes32 slot = _initializableStorageSlot();
assembly {
$.slot := slot
}
}
}
@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.22;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC-1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// On the first call to nonReentrant, _status will be NOT_ENTERED
if ($._status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
$._status = ENTERED;
}
function _nonReentrantAfter() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
$._status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}
@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/interfaces/IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1967.sol)
pragma solidity >=0.4.11;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
@openzeppelin/contracts/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC1822.sol)
pragma solidity >=0.4.16;
/**
* @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.21;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This library provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit IERC1967.Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit IERC1967.AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the ERC-1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit IERC1967.BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
@openzeppelin/contracts/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/beacon/IBeacon.sol)
pragma solidity >=0.4.16;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
@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/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, bytes memory returndata) = recipient.call{value: amount}("");
if (!success) {
_revert(returndata);
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
revert(add(returndata, 0x20), mload(returndata))
}
} else {
revert Errors.FailedCall();
}
}
}
@openzeppelin/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
@openzeppelin/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
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/INavOracleAutomation.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
interface INavOracleAutomation {
function vault() external view returns (address);
function lossManager() external view returns (address);
function mzusd() external view returns (address);
}
contracts/interfaces/IReservoir.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
interface IReservoir {
function deposit(uint256 amount) external;
function withdraw(uint256 amount, address to) external;
function usdc() external view returns (address);
function authority() external view returns (address);
function pauseManager() external view returns (address);
}
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/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
}
contracts/pause/PauseManagedUpgradeable.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {IPauseManager} from "./IPauseManager.sol";
import {PauseCategory} from "./PauseCategory.sol";
/// @title PauseManagedUpgradeable
/// @notice Base contract for category-based pause checks via PauseManager.
/// @dev PauseManager address is configured once during initialization in v1.
/// Rotation is not exposed by this base contract and must be designed explicitly if needed.
abstract contract PauseManagedUpgradeable is Initializable {
/// @dev Kept private to avoid direct state mutation from inheritors; use pauseManager() getter for reads.
IPauseManager private _pauseManager;
event PauseManagerUpdated(address indexed newManager);
error PauseManagerZeroAddress();
error CategoryPaused(PauseCategory category);
/// @notice Initialize PauseManaged with a PauseManager address.
/// @dev One-time wiring in v1; no public/external setter is provided for post-init replacement.
function __PauseManaged_init(address pauseManager_) internal onlyInitializing {
_setPauseManager(pauseManager_);
}
/// @notice Returns the current PauseManager address.
/// @dev Exposed for integrations and cross-contract consistency checks.
function pauseManager() public view returns (address) {
return address(_pauseManager);
}
/// @notice Internal setter for PauseManager address.
function _setPauseManager(address pauseManager_) internal {
if (pauseManager_ == address(0)) revert PauseManagerZeroAddress();
_pauseManager = IPauseManager(pauseManager_);
emit PauseManagerUpdated(pauseManager_);
}
/// @notice Reverts if a category is paused (global or per-contract).
modifier whenNotPaused(PauseCategory category) {
if (_pauseManager.isPaused(address(this), category)) {
revert CategoryPaused(category);
}
_;
}
uint256[49] private __gap;
}
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.