Skip to content
Verified contractExactGPL-2.0-or-later

LotusGovernor

Address0xef65eaaf68e49b24c593707442054e950feced6a
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.28

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
GPL-2.0-or-later
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,429,736
Creation transaction
0x06d4fb3c82…b30980d086

src/governance/LotusGovernor.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;

import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";

import {Id, ILotus, MarketParams, Tranche} from "../interfaces/ILotus.sol";
import {MarketParamsLib} from "../libraries/MarketParamsLib.sol";
import {PendingLib} from "../libraries/PendingLib.sol";
import {ILotusGovernor} from "./interfaces/ILotusGovernor.sol";

/// @title LotusGovernor
/// @notice Timelock policy executor for Lotus risk, module, and ownership actions.
/// @dev Enforces an asymmetric timelock policy: risk-reducing actions are instant, risk-increasing
///      actions require a 24h timelock, and irreversible actions require a 72h timelock.
///      A Guardian role can revoke any pending timelocked action but cannot enact anything.
contract LotusGovernor is ILotusGovernor {
    using PendingLib for PendingLib.PendingAddress;
    using PendingLib for PendingLib.PendingUint64;
    using PendingLib for PendingLib.PendingUint128;
    using PendingLib for PendingLib.PendingMarketHook;
    using PendingLib for PendingLib.PendingUpgrade;
    using MarketParamsLib for MarketParams;

    /* CONSTANTS */

    /// @inheritdoc ILotusGovernor
    uint256 public constant MIN_TIMELOCK = 1 days;

    /// @inheritdoc ILotusGovernor
    uint256 public constant MIN_LONG_TIMELOCK = 3 days;

    /* IMMUTABLES */

    /// @inheritdoc ILotusGovernor
    ILotus public immutable LOTUS;

    /// @inheritdoc ILotusGovernor
    uint256 public immutable TIMELOCK;

    /// @inheritdoc ILotusGovernor
    uint256 public immutable LONG_TIMELOCK;

    /* STORAGE */

    /// @inheritdoc ILotusGovernor
    address public owner;

    /// @inheritdoc ILotusGovernor
    address public guardian;

    /* PENDING STATE: 24H TIMELOCKED */

    /// @dev Pending fee recipient update, executable after `TIMELOCK`.
    PendingLib.PendingAddress public pendingFeeRecipient;
    /// @dev Pending per-market, per-tranche fee update, executable after `TIMELOCK`.
    mapping(Id id => mapping(uint256 trancheIndex => PendingLib.PendingUint64)) public pendingFee;
    /// @dev Pending per-token flash-loan fee update, executable after `TIMELOCK`.
    mapping(address token => PendingLib.PendingUint64) public pendingFlashLoanFee;
    /// @dev Pending global borrow LTV buffer update, executable after `TIMELOCK`.
    PendingLib.PendingUint64 public pendingBorrowLtvBuffer;
    /// @dev Pending risk-engine enable action, executable after `TIMELOCK`.
    mapping(address riskEngine => PendingLib.PendingAddress) public pendingRiskEngine;
    /// @dev Pending LLTV enable action, executable after `TIMELOCK`.
    mapping(uint128 lltv => PendingLib.PendingUint128) public pendingLltv;
    /// @dev Pending liquidation-module enable action, executable after `TIMELOCK`.
    mapping(address liquidationModule => PendingLib.PendingAddress) public pendingLiquidationModule;
    /// @dev Pending module-manager enable action, executable after `TIMELOCK`.
    mapping(address manager => PendingLib.PendingAddress) public pendingModuleManager;
    /// @dev Pending market hook update, executable after `TIMELOCK`.
    mapping(Id id => PendingLib.PendingMarketHook) public pendingMarketHook;
    /// @dev Pending repay-cooldown exemption grant, executable after `TIMELOCK`.
    mapping(address account => PendingLib.PendingAddress) public pendingBorrowCooldownExempt;

    /* PENDING STATE: 72H TIMELOCKED */

    /// @dev Pending Lotus owner transfer, executable after `LONG_TIMELOCK`.
    PendingLib.PendingAddress public pendingLotusOwner;
    /// @dev Pending governor owner transfer, executable after `LONG_TIMELOCK`.
    PendingLib.PendingAddress public pendingGovernorOwner;
    /// @dev Pending guardian update, executable after `LONG_TIMELOCK`.
    PendingLib.PendingAddress public pendingGuardian;
    /// @dev Pending module upgrade keyed by module address, executable after `LONG_TIMELOCK`.
    mapping(address module => PendingLib.PendingUpgrade) public pendingModuleUpgrade;
    /// @dev Pending module ownership transfer keyed by module address, executable after `LONG_TIMELOCK`.
    mapping(address module => PendingLib.PendingAddress) public pendingModuleOwnership;

    /* CONSTRUCTOR */

    /// @param lotus The Lotus protocol governed by this contract.
    /// @param initialOwner The initial governor owner.
    /// @param initialGuardian The initial guardian allowed to revoke pending actions.
    /// @param timelock The standard timelock for governance actions. Must be at least `MIN_TIMELOCK`.
    /// @param longTimelock The long timelock for ownership, guardian, and upgrade actions. Must be at least
    ///        `MIN_LONG_TIMELOCK` and no shorter than `timelock`.
    constructor(ILotus lotus, address initialOwner, address initialGuardian, uint256 timelock, uint256 longTimelock) {
        if (address(lotus) == address(0) || initialOwner == address(0)) revert ZeroAddress();
        if (timelock < MIN_TIMELOCK || longTimelock < MIN_LONG_TIMELOCK || longTimelock < timelock) {
            revert InvalidTimelock();
        }

        LOTUS = lotus;
        TIMELOCK = timelock;
        LONG_TIMELOCK = longTimelock;
        owner = initialOwner;
        guardian = initialGuardian;

        emit GovernorOwnerUpdated(initialOwner);
        emit GuardianUpdated(initialGuardian);
    }

    /* MODIFIERS */

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }

    modifier onlyOwnerOrGuardian() {
        if (msg.sender != owner && msg.sender != guardian) revert NotOwnerOrGuardian();
        _;
    }

    modifier onlyGuardian() {
        if (msg.sender != guardian) revert NotGuardian();
        _;
    }

    /* INSTANT RISK-REDUCING FUNCTIONS */

    /// @inheritdoc ILotusGovernor
    function setFee(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        uint64 newFee,
        bytes calldata riskEngineData
    ) external onlyOwner {
        Id id = marketParams.id();
        Tranche memory tranche = LOTUS.getMarketTranche(id, trancheIndex);
        if (newFee >= tranche.fee) revert TimelockRequired();
        LOTUS.setFee(marketParams, trancheIndex, newFee, riskEngineData);
    }

    /// @inheritdoc ILotusGovernor
    function setFlashLoanFee(address token, uint64 newFee) external onlyOwner {
        uint64 currentFee = LOTUS.flashLoanFee(token);
        if (newFee >= currentFee) revert TimelockRequired();
        LOTUS.setFlashLoanFee(token, newFee);
    }

    /// @inheritdoc ILotusGovernor
    function setBorrowLtvBuffer(uint64 newBuffer) external onlyOwner {
        if (newBuffer <= LOTUS.borrowLtvBuffer()) revert TimelockRequired();
        LOTUS.setBorrowLtvBuffer(newBuffer);
    }

    /// @inheritdoc ILotusGovernor
    function disableModuleManager(address manager) external onlyOwner {
        LOTUS.disableModuleManager(manager);
    }

    /// @inheritdoc ILotusGovernor
    function setPaused(MarketParams memory marketParams, bool global, bool paused) external onlyOwner {
        LOTUS.setPaused(marketParams, global, paused);
    }

    /// @inheritdoc ILotusGovernor
    function clearBorrowCooldown(Id id, uint256 trancheIndex) external onlyOwner {
        LOTUS.clearBorrowCooldown(id, trancheIndex);
    }

    /// @inheritdoc ILotusGovernor
    function setBorrowCooldownExempt(address account, bool exempt) external onlyOwner {
        if (exempt) revert TimelockRequired();
        LOTUS.setBorrowCooldownExempt(account, false);
    }

    /* 24H TIMELOCKED: FEE INCREASE */

    /// @inheritdoc ILotusGovernor
    function submitSetFee(MarketParams memory marketParams, uint256 trancheIndex, uint64 newFee, bytes calldata)
        external
        onlyOwner
    {
        Id id = marketParams.id();
        PendingLib.PendingUint64 storage p = pendingFee[id][trancheIndex];
        PendingLib.assertNotPending(p.validAt);
        uint64 validAt = p.update(newFee, TIMELOCK);
        emit SetFeeSubmitted(id, trancheIndex, newFee, validAt);
    }

    /// @inheritdoc ILotusGovernor
    function acceptSetFee(MarketParams memory marketParams, uint256 trancheIndex, bytes calldata riskEngineData)
        external
        onlyOwner
    {
        Id id = marketParams.id();
        PendingLib.PendingUint64 storage p = pendingFee[id][trancheIndex];
        PendingLib.assertExecutable(p.validAt);
        uint64 newFee = p.value;
        p.clear();
        LOTUS.setFee(marketParams, trancheIndex, newFee, riskEngineData);
        emit SetFeeAccepted(id, trancheIndex, newFee);
    }

    /// @inheritdoc ILotusGovernor
    function revokeSetFee(MarketParams memory marketParams, uint256 trancheIndex) external onlyOwnerOrGuardian {
        Id id = marketParams.id();
        PendingLib.PendingUint64 storage p = pendingFee[id][trancheIndex];
        PendingLib.assertIsPending(p.validAt);
        p.clear();
        emit SetFeeRevoked(id, trancheIndex, msg.sender);
    }

    /* 24H TIMELOCKED: FEE RECIPIENT */

    /// @inheritdoc ILotusGovernor
    function submitSetFeeRecipient(address newFeeRecipient) external onlyOwner {
        if (newFeeRecipient == address(0) || newFeeRecipient == address(LOTUS)) {
            revert InvalidFeeRecipient(newFeeRecipient);
        }
        PendingLib.assertNotPending(pendingFeeRecipient.validAt);
        pendingFeeRecipient.update(newFeeRecipient, TIMELOCK);
        emit SetFeeRecipientSubmitted(newFeeRecipient, pendingFeeRecipient.validAt);
    }

    /// @inheritdoc ILotusGovernor
    function acceptSetFeeRecipient() external onlyOwner {
        PendingLib.assertExecutable(pendingFeeRecipient.validAt);
        address newFeeRecipient = pendingFeeRecipient.value;
        pendingFeeRecipient.clear();
        LOTUS.setFeeRecipient(newFeeRecipient);
        emit SetFeeRecipientAccepted(newFeeRecipient);
    }

    /// @inheritdoc ILotusGovernor
    function revokeSetFeeRecipient() external onlyOwnerOrGuardian {
        PendingLib.assertIsPending(pendingFeeRecipient.validAt);
        pendingFeeRecipient.clear();
        emit SetFeeRecipientRevoked(msg.sender);
    }

    /* 24H TIMELOCKED: FLASH LOAN FEE INCREASE */

    /// @inheritdoc ILotusGovernor
    function submitSetFlashLoanFee(address token, uint64 newFee) external onlyOwner {
        PendingLib.PendingUint64 storage p = pendingFlashLoanFee[token];
        PendingLib.assertNotPending(p.validAt);
        uint64 validAt = p.update(newFee, TIMELOCK);
        emit SetFlashLoanFeeSubmitted(token, newFee, validAt);
    }

    /// @inheritdoc ILotusGovernor
    function acceptSetFlashLoanFee(address token) external onlyOwner {
        PendingLib.PendingUint64 storage p = pendingFlashLoanFee[token];
        PendingLib.assertExecutable(p.validAt);
        uint64 newFee = p.value;
        p.clear();
        LOTUS.setFlashLoanFee(token, newFee);
        emit SetFlashLoanFeeAccepted(token, newFee);
    }

    /// @inheritdoc ILotusGovernor
    function revokeSetFlashLoanFee(address token) external onlyOwnerOrGuardian {
        PendingLib.PendingUint64 storage p = pendingFlashLoanFee[token];
        PendingLib.assertIsPending(p.validAt);
        p.clear();
        emit SetFlashLoanFeeRevoked(token, msg.sender);
    }

    /* 24H TIMELOCKED: BORROW LTV BUFFER DECREASE */

    /// @inheritdoc ILotusGovernor
    function submitSetBorrowLtvBuffer(uint64 newBuffer) external onlyOwner {
        PendingLib.PendingUint64 storage p = pendingBorrowLtvBuffer;
        PendingLib.assertNotPending(p.validAt);
        uint64 validAt = p.update(newBuffer, TIMELOCK);
        emit SetBorrowLtvBufferSubmitted(newBuffer, validAt);
    }

    /// @inheritdoc ILotusGovernor
    function acceptSetBorrowLtvBuffer() external onlyOwner {
        PendingLib.PendingUint64 storage p = pendingBorrowLtvBuffer;
        PendingLib.assertExecutable(p.validAt);
        uint64 newBuffer = p.value;
        p.clear();
        LOTUS.setBorrowLtvBuffer(newBuffer);
        emit SetBorrowLtvBufferAccepted(newBuffer);
    }

    /// @inheritdoc ILotusGovernor
    function revokeSetBorrowLtvBuffer() external onlyOwnerOrGuardian {
        PendingLib.PendingUint64 storage p = pendingBorrowLtvBuffer;
        PendingLib.assertIsPending(p.validAt);
        p.clear();
        emit SetBorrowLtvBufferRevoked(msg.sender);
    }

    /* 24H TIMELOCKED: ENABLE RISK ENGINE */

    /// @inheritdoc ILotusGovernor
    function submitEnableRiskEngine(address riskEngine) external onlyOwner {
        PendingLib.PendingAddress storage p = pendingRiskEngine[riskEngine];
        PendingLib.assertNotPending(p.validAt);
        uint64 validAt = p.update(riskEngine, TIMELOCK);
        emit EnableRiskEngineSubmitted(riskEngine, validAt);
    }

    /// @inheritdoc ILotusGovernor
    function acceptEnableRiskEngine(address riskEngine) external onlyOwner {
        PendingLib.PendingAddress storage p = pendingRiskEngine[riskEngine];
        PendingLib.assertExecutable(p.validAt);
        p.clear();
        LOTUS.enableRiskEngine(riskEngine);
        emit EnableRiskEngineAccepted(riskEngine);
    }

    /// @inheritdoc ILotusGovernor
    function revokeEnableRiskEngine(address riskEngine) external onlyOwnerOrGuardian {
        PendingLib.PendingAddress storage p = pendingRiskEngine[riskEngine];
        PendingLib.assertIsPending(p.validAt);
        p.clear();
        emit EnableRiskEngineRevoked(riskEngine, msg.sender);
    }

    /* 24H TIMELOCKED: ENABLE LLTV */

    /// @inheritdoc ILotusGovernor
    function submitEnableLltv(uint128 lltv) external onlyOwner {
        PendingLib.PendingUint128 storage p = pendingLltv[lltv];
        PendingLib.assertNotPending(p.validAt);
        uint64 validAt = p.update(lltv, TIMELOCK);
        emit EnableLltvSubmitted(lltv, validAt);
    }

    /// @inheritdoc ILotusGovernor
    function acceptEnableLltv(uint128 lltv) external onlyOwner {
        PendingLib.PendingUint128 storage p = pendingLltv[lltv];
        PendingLib.assertExecutable(p.validAt);
        p.clear();
        LOTUS.enableLltv(lltv);
        emit EnableLltvAccepted(lltv);
    }

    /// @inheritdoc ILotusGovernor
    function revokeEnableLltv(uint128 lltv) external onlyOwnerOrGuardian {
        PendingLib.PendingUint128 storage p = pendingLltv[lltv];
        PendingLib.assertIsPending(p.validAt);
        p.clear();
        emit EnableLltvRevoked(lltv, msg.sender);
    }

    /* 24H TIMELOCKED: ENABLE LIQUIDATION MODULE */

    /// @inheritdoc ILotusGovernor
    function submitEnableLiquidationModule(address liquidationModule) external onlyOwner {
        PendingLib.PendingAddress storage p = pendingLiquidationModule[liquidationModule];
        PendingLib.assertNotPending(p.validAt);
        uint64 validAt = p.update(liquidationModule, TIMELOCK);
        emit EnableLiquidationModuleSubmitted(liquidationModule, validAt);
    }

    /// @inheritdoc ILotusGovernor
    function acceptEnableLiquidationModule(address liquidationModule) external onlyOwner {
        PendingLib.PendingAddress storage p = pendingLiquidationModule[liquidationModule];
        PendingLib.assertExecutable(p.validAt);
        p.clear();
        LOTUS.enableLiquidationModule(liquidationModule);
        emit EnableLiquidationModuleAccepted(liquidationModule);
    }

    /// @inheritdoc ILotusGovernor
    function revokeEnableLiquidationModule(address liquidationModule) external onlyOwnerOrGuardian {
        PendingLib.PendingAddress storage p = pendingLiquidationModule[liquidationModule];
        PendingLib.assertIsPending(p.validAt);
        p.clear();
        emit EnableLiquidationModuleRevoked(liquidationModule, msg.sender);
    }

    /* 24H TIMELOCKED: ENABLE MODULE MANAGER */

    /// @inheritdoc ILotusGovernor
    function submitEnableModuleManager(address manager) external onlyOwner {
        PendingLib.PendingAddress storage p = pendingModuleManager[manager];
        PendingLib.assertNotPending(p.validAt);
        uint64 validAt = p.update(manager, TIMELOCK);
        emit EnableModuleManagerSubmitted(manager, validAt);
    }

    /// @inheritdoc ILotusGovernor
    function acceptEnableModuleManager(address manager) external onlyOwner {
        PendingLib.PendingAddress storage p = pendingModuleManager[manager];
        PendingLib.assertExecutable(p.validAt);
        p.clear();
        LOTUS.enableModuleManager(manager);
        emit EnableModuleManagerAccepted(manager);
    }

    /// @inheritdoc ILotusGovernor
    function revokeEnableModuleManager(address manager) external onlyOwnerOrGuardian {
        PendingLib.PendingAddress storage p = pendingModuleManager[manager];
        PendingLib.assertIsPending(p.validAt);
        p.clear();
        emit EnableModuleManagerRevoked(manager, msg.sender);
    }

    /* 24H TIMELOCKED: SET MARKET HOOK */

    /// @inheritdoc ILotusGovernor
    function submitSetMarketHook(MarketParams memory marketParams, address hook, uint256 permissions)
        external
        onlyOwner
    {
        Id id = marketParams.id();
        PendingLib.PendingMarketHook storage p = pendingMarketHook[id];
        PendingLib.assertNotPending(p.validAt);
        uint64 validAt = p.update(hook, permissions, TIMELOCK);
        emit SetMarketHookSubmitted(id, hook, permissions, validAt);
    }

    /// @inheritdoc ILotusGovernor
    function acceptSetMarketHook(MarketParams memory marketParams) external onlyOwner {
        Id id = marketParams.id();
        PendingLib.PendingMarketHook storage p = pendingMarketHook[id];
        PendingLib.assertExecutable(p.validAt);
        address hook = p.hook;
        uint256 permissions = p.permissions;
        p.clear();
        LOTUS.setMarketHook(marketParams, hook, permissions);
        emit SetMarketHookAccepted(id, hook, permissions);
    }

    /// @inheritdoc ILotusGovernor
    function revokeSetMarketHook(MarketParams memory marketParams) external onlyOwnerOrGuardian {
        Id id = marketParams.id();
        PendingLib.PendingMarketHook storage p = pendingMarketHook[id];
        PendingLib.assertIsPending(p.validAt);
        p.clear();
        emit SetMarketHookRevoked(id, msg.sender);
    }

    /* 24H TIMELOCKED: BORROW COOLDOWN EXEMPTION */

    /// @inheritdoc ILotusGovernor
    function submitSetBorrowCooldownExempt(address account) external onlyOwner {
        PendingLib.PendingAddress storage p = pendingBorrowCooldownExempt[account];
        PendingLib.assertNotPending(p.validAt);
        uint64 validAt = p.update(account, TIMELOCK);
        emit SetBorrowCooldownExemptSubmitted(account, validAt);
    }

    /// @inheritdoc ILotusGovernor
    function acceptSetBorrowCooldownExempt(address account) external onlyOwner {
        PendingLib.PendingAddress storage p = pendingBorrowCooldownExempt[account];
        PendingLib.assertExecutable(p.validAt);
        p.clear();
        LOTUS.setBorrowCooldownExempt(account, true);
        emit SetBorrowCooldownExemptAccepted(account);
    }

    /// @inheritdoc ILotusGovernor
    function revokeSetBorrowCooldownExempt(address account) external onlyOwnerOrGuardian {
        PendingLib.PendingAddress storage p = pendingBorrowCooldownExempt[account];
        PendingLib.assertIsPending(p.validAt);
        p.clear();
        emit SetBorrowCooldownExemptRevoked(account, msg.sender);
    }

    /* 72H TIMELOCKED: LOTUS OWNERSHIP TRANSFER */

    /// @inheritdoc ILotusGovernor
    function submitTransferLotusOwnership(address newOwner) external onlyOwner {
        PendingLib.assertNotPending(pendingLotusOwner.validAt);
        pendingLotusOwner.update(newOwner, LONG_TIMELOCK);
        emit TransferLotusOwnershipSubmitted(newOwner, pendingLotusOwner.validAt);
    }

    /// @inheritdoc ILotusGovernor
    function acceptTransferLotusOwnership() external onlyOwner {
        PendingLib.assertExecutable(pendingLotusOwner.validAt);
        address newOwner = pendingLotusOwner.value;
        pendingLotusOwner.clear();
        LOTUS.transferOwnership(newOwner);
        emit TransferLotusOwnershipAccepted(newOwner);
    }

    /// @inheritdoc ILotusGovernor
    function acceptLotusOwnership() external onlyOwner {
        LOTUS.acceptOwnership();
    }

    /// @inheritdoc ILotusGovernor
    function revokeTransferLotusOwnership() external onlyOwnerOrGuardian {
        PendingLib.assertIsPending(pendingLotusOwner.validAt);
        pendingLotusOwner.clear();
        emit TransferLotusOwnershipRevoked(msg.sender);
    }

    /* 72H TIMELOCKED: GOVERNOR OWNERSHIP TRANSFER (2-STEP) */

    /// @inheritdoc ILotusGovernor
    function submitTransferGovernorOwnership(address newOwner) external onlyOwner {
        PendingLib.assertNotPending(pendingGovernorOwner.validAt);
        pendingGovernorOwner.update(newOwner, LONG_TIMELOCK);
        emit TransferGovernorOwnershipSubmitted(newOwner, pendingGovernorOwner.validAt);
    }

    /// @inheritdoc ILotusGovernor
    /// @dev Must be called by the pending new owner (2-step acceptance).
    function acceptTransferGovernorOwnership() external {
        PendingLib.assertExecutable(pendingGovernorOwner.validAt);
        if (msg.sender != pendingGovernorOwner.value) revert NotPendingOwner();
        owner = pendingGovernorOwner.value;
        pendingGovernorOwner.clear();
        emit GovernorOwnerUpdated(owner);
    }

    /// @inheritdoc ILotusGovernor
    function revokeTransferGovernorOwnership() external onlyGuardian {
        PendingLib.assertIsPending(pendingGovernorOwner.validAt);
        pendingGovernorOwner.clear();
        emit TransferGovernorOwnershipRevoked(msg.sender);
    }

    /* 72H TIMELOCKED: GUARDIAN CHANGE */

    /// @inheritdoc ILotusGovernor
    function submitSetGuardian(address newGuardian) external onlyOwner {
        PendingLib.assertNotPending(pendingGuardian.validAt);
        pendingGuardian.update(newGuardian, LONG_TIMELOCK);
        emit SetGuardianSubmitted(newGuardian, pendingGuardian.validAt);
    }

    /// @inheritdoc ILotusGovernor
    function acceptSetGuardian() external onlyOwner {
        PendingLib.assertExecutable(pendingGuardian.validAt);
        guardian = pendingGuardian.value;
        pendingGuardian.clear();
        emit GuardianUpdated(guardian);
    }

    /// @inheritdoc ILotusGovernor
    function revokeSetGuardian() external onlyOwnerOrGuardian {
        PendingLib.assertIsPending(pendingGuardian.validAt);
        pendingGuardian.clear();
        emit SetGuardianRevoked(msg.sender);
    }

    /* 72H TIMELOCKED: MODULE UPGRADES */

    /// @inheritdoc ILotusGovernor
    function submitModuleUpgrade(address module, address newImplementation, bytes calldata data) external onlyOwner {
        PendingLib.PendingUpgrade storage p = pendingModuleUpgrade[module];
        PendingLib.assertNotPending(p.validAt);
        bytes32 dataHash = keccak256(data);
        uint64 validAt = p.update(newImplementation, dataHash, LONG_TIMELOCK);
        emit ModuleUpgradeSubmitted(module, newImplementation, data, dataHash, validAt);
    }

    /// @inheritdoc ILotusGovernor
    function acceptModuleUpgrade(address module, bytes calldata data) external onlyOwner {
        PendingLib.PendingUpgrade storage p = pendingModuleUpgrade[module];
        PendingLib.assertExecutable(p.validAt);
        bytes32 dataHash = keccak256(data);
        if (dataHash != p.dataHash) revert DataHashMismatch();
        address impl = p.newImplementation;
        p.clear();
        UUPSUpgradeable(module).upgradeToAndCall(impl, data);
        emit ModuleUpgradeAccepted(module, impl, dataHash);
    }

    /// @inheritdoc ILotusGovernor
    function revokeModuleUpgrade(address module) external onlyOwnerOrGuardian {
        PendingLib.PendingUpgrade storage p = pendingModuleUpgrade[module];
        PendingLib.assertIsPending(p.validAt);
        p.clear();
        emit ModuleUpgradeRevoked(module, msg.sender);
    }

    /* 72H TIMELOCKED: MODULE OWNERSHIP TRANSFER (2-STEP) */

    /// @inheritdoc ILotusGovernor
    function submitTransferModuleOwnership(address module, address newOwner) external onlyOwner {
        PendingLib.PendingAddress storage p = pendingModuleOwnership[module];
        PendingLib.assertNotPending(p.validAt);
        uint64 validAt = p.update(newOwner, LONG_TIMELOCK);
        emit TransferModuleOwnershipSubmitted(module, newOwner, validAt);
    }

    /// @inheritdoc ILotusGovernor
    function acceptTransferModuleOwnership(address module) external onlyOwner {
        PendingLib.PendingAddress storage p = pendingModuleOwnership[module];
        PendingLib.assertExecutable(p.validAt);
        address newOwner = p.value;
        p.clear();
        Ownable2StepUpgradeable(module).transferOwnership(newOwner);
        emit TransferModuleOwnershipAccepted(module, newOwner);
    }

    /// @inheritdoc ILotusGovernor
    function revokeTransferModuleOwnership(address module) external onlyOwnerOrGuardian {
        PendingLib.PendingAddress storage p = pendingModuleOwnership[module];
        PendingLib.assertIsPending(p.validAt);
        p.clear();
        emit TransferModuleOwnershipRevoked(module, msg.sender);
    }

    /// @inheritdoc ILotusGovernor
    function acceptModuleOwnership(address module) external onlyOwner {
        Ownable2StepUpgradeable(module).acceptOwnership();
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

import {OwnableUpgradeable} from "./OwnableUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2StepUpgradeable is Initializable, OwnableUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Ownable2Step
    struct Ownable2StepStorage {
        address _pendingOwner;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable2Step")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant Ownable2StepStorageLocation = 0x237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c00;

    function _getOwnable2StepStorage() private pure returns (Ownable2StepStorage storage $) {
        assembly {
            $.slot := Ownable2StepStorageLocation
        }
    }

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    function __Ownable2Step_init() internal onlyInitializing {
    }

    function __Ownable2Step_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        Ownable2StepStorage storage $ = _getOwnable2StepStorage();
        return $._pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        Ownable2StepStorage storage $ = _getOwnable2StepStorage();
        $._pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        Ownable2StepStorage storage $ = _getOwnable2StepStorage();
        delete $._pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Ownable
    struct OwnableStorage {
        address _owner;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;

    function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
        assembly {
            $.slot := OwnableStorageLocation
        }
    }

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    function __Ownable_init(address initialOwner) internal onlyInitializing {
        __Ownable_init_unchained(initialOwner);
    }

    function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        OwnableStorage storage $ = _getOwnableStorage();
        return $._owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        OwnableStorage storage $ = _getOwnableStorage();
        address oldOwner = $._owner;
        $._owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 reininitialization) 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 Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.20;

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 ERC1967) 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 ERC1167 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 ERC1822 {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 ERC1967-compliant implementation pointing to self.
     * See {_onlyProxy}.
     */
    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 ERC1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol

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

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC1822.sol)

pragma solidity ^0.8.20;

/**
 * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.20;

import {IBeacon} from "../beacon/IBeacon.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This abstract contract provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
 */
library ERC1967Utils {
    // We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
    // This will be fixed in Solidity 0.8.21. At that point we should remove these events.
    /**
     * @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);

    /**
     * @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 EIP1967 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 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 EIP1967) 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 EIP1967 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 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 EIP1967 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 BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}

lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {UpgradeableBeacon} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

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

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

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedInnerCall();

    /**
     * @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 AddressInsufficientBalance(address(this));
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

    /**
     * @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
     * {FailedInnerCall} 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 AddressInsufficientBalance(address(this));
        }
        (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 {FailedInnerCall}) 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 {FailedInnerCall} 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 {FailedInnerCall}.
     */
    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
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert FailedInnerCall();
        }
    }
}

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     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;
 *     }
 * }
 * ```
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 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) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            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) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            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) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}

src/access/TwoStepOwnable.sol

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

/// @title ITwoStepOwnable
/// @notice Two-step ownership interface. Host interfaces extend this so the mixin implements it once.
interface ITwoStepOwnable {
    /// @notice Emitted when a two-step ownership transfer is started.
    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    /// @notice Emitted when ownership changes (accept or renounce).
    event OwnerUpdated(address indexed newOwner);

    /// @notice Caller is not the owner.
    error NotOwner();

    /// @notice Caller is not the pending owner.
    error NotPendingOwner();

    /// @notice The current owner.
    function owner() external view returns (address);

    /// @notice The pending owner of a two-step transfer.
    function pendingOwner() external view returns (address);

    /// @notice Starts a two-step ownership transfer. The new owner must call `acceptOwnership`.
    function transferOwnership(address newOwner) external;

    /// @notice Completes a two-step ownership transfer. Callable only by the pending owner.
    function acceptOwnership() external;

    /// @notice Renounces ownership, setting the owner to the zero address.
    function renounceOwnership() external;
}

/// @title TwoStepOwnable
/// @notice Two-step ownership transfer with a separate renounce, mirroring OpenZeppelin's Ownable2Step.
/// @dev ERC-7201 namespaced storage so this composes with upgradeable and non-upgradeable hosts, and
///      alongside a TwoStepOperator role, with no storage-layout clashes. Seed the initial owner from the
///      host constructor or initializer via `_initializeOwner`.
abstract contract TwoStepOwnable is ITwoStepOwnable {
    /// @custom:storage-location erc7201:lotus.storage.TwoStepOwnable
    struct OwnableStorage {
        address owner;
        address pendingOwner;
    }

    // keccak256(abi.encode(uint256(keccak256("lotus.storage.TwoStepOwnable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant _STORAGE = 0xfaec8a094acaf62210bd0812262aaaff8760ca5d3f50907b79cda40ef2806d00;

    function _ownableStorage() private pure returns (OwnableStorage storage $) {
        assembly {
            $.slot := _STORAGE
        }
    }

    modifier onlyOwner() {
        if (msg.sender != _ownableStorage().owner) revert NotOwner();
        _;
    }

    /// @inheritdoc ITwoStepOwnable
    function owner() public view virtual override returns (address) {
        return _ownableStorage().owner;
    }

    /// @inheritdoc ITwoStepOwnable
    function pendingOwner() public view virtual override returns (address) {
        return _ownableStorage().pendingOwner;
    }

    /// @inheritdoc ITwoStepOwnable
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        OwnableStorage storage $ = _ownableStorage();
        $.pendingOwner = newOwner;
        emit OwnershipTransferStarted($.owner, newOwner);
    }

    /// @inheritdoc ITwoStepOwnable
    function acceptOwnership() public virtual override {
        if (msg.sender != _ownableStorage().pendingOwner) revert NotPendingOwner();
        _setOwner(msg.sender);
    }

    /// @inheritdoc ITwoStepOwnable
    function renounceOwnership() public virtual override onlyOwner {
        _setOwner(address(0));
    }

    /// @dev Seeds the owner. Call once from the host constructor or initializer.
    function _initializeOwner(address initialOwner) internal {
        _setOwner(initialOwner);
    }

    function _setOwner(address newOwner) internal {
        OwnableStorage storage $ = _ownableStorage();
        $.owner = newOwner;
        delete $.pendingOwner;
        emit OwnerUpdated(newOwner);
    }
}

src/governance/interfaces/ILotusGovernor.sol

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

import {Id, ILotus, MarketParams} from "../../interfaces/ILotus.sol";

/// @title ILotusGovernor
/// @notice Interface for the Lotus Governor contract - an external timelock wrapper
///         that sits between a multisig/DAO and the Lotus protocol, enforcing asymmetric
///         timelocks on governance actions.
interface ILotusGovernor {
    /* ERRORS */

    /// @notice Risk-increasing action requires the submit/accept timelock path.
    error TimelockRequired();

    /// @notice Caller is not the governor owner.
    error NotOwner();

    /// @notice Caller is neither the governor owner nor the guardian.
    error NotOwnerOrGuardian();

    /// @notice Caller is not the guardian.
    error NotGuardian();

    /// @notice Pending governor owner does not match the caller in the two-step transfer.
    error NotPendingOwner();

    /// @notice Constructor received a timelock below its minimum or `longTimelock < timelock`.
    error InvalidTimelock();

    /// @notice Zero address provided for a required argument.
    error ZeroAddress();

    /// @notice Fee recipient is the zero address or the Lotus contract itself.
    /// @param feeRecipient The invalid fee recipient.
    error InvalidFeeRecipient(address feeRecipient);

    /// @notice Data hash at accept time does not match the submitted hash.
    error DataHashMismatch();

    /* SUBMIT EVENTS */

    /// @notice Emitted when a fee increase or same-fee update is submitted for timelocked acceptance.
    /// @param id The market whose tranche fee update was submitted.
    /// @param trancheIndex The tranche whose fee update was submitted.
    /// @param newFee The submitted fee.
    /// @param validAt The timestamp when the update can be accepted.
    event SetFeeSubmitted(Id indexed id, uint256 indexed trancheIndex, uint64 newFee, uint64 validAt);

    /// @notice Emitted when a fee-recipient update is submitted.
    /// @param newFeeRecipient The submitted fee recipient.
    /// @param validAt The timestamp when the update can be accepted.
    event SetFeeRecipientSubmitted(address indexed newFeeRecipient, uint64 validAt);

    /// @notice Emitted when a flash-loan fee update is submitted.
    /// @param token The token whose flash-loan fee is being changed.
    /// @param newFee The submitted flash-loan fee.
    /// @param validAt The timestamp when the update can be accepted.
    event SetFlashLoanFeeSubmitted(address indexed token, uint64 newFee, uint64 validAt);

    /// @notice Emitted when a borrow LTV buffer decrease is submitted.
    /// @param newBuffer The submitted borrow LTV buffer.
    /// @param validAt The timestamp when the update can be accepted.
    event SetBorrowLtvBufferSubmitted(uint64 newBuffer, uint64 validAt);

    /// @notice Emitted when enabling a risk engine is submitted.
    /// @param riskEngine The risk engine pending enablement.
    /// @param validAt The timestamp when the enablement can be accepted.
    event EnableRiskEngineSubmitted(address indexed riskEngine, uint64 validAt);

    /// @notice Emitted when enabling an LLTV is submitted.
    /// @param lltv The LLTV pending enablement.
    /// @param validAt The timestamp when the enablement can be accepted.
    event EnableLltvSubmitted(uint128 indexed lltv, uint64 validAt);

    /// @notice Emitted when enabling a liquidation module is submitted.
    /// @param module The liquidation module pending enablement.
    /// @param validAt The timestamp when the enablement can be accepted.
    event EnableLiquidationModuleSubmitted(address indexed module, uint64 validAt);

    /// @notice Emitted when enabling a module manager is submitted.
    /// @param manager The module manager pending enablement.
    /// @param validAt The timestamp when the enablement can be accepted.
    event EnableModuleManagerSubmitted(address indexed manager, uint64 validAt);

    /// @notice Emitted when a market hook update is submitted.
    /// @param id The market whose hook update was submitted.
    /// @param hook The hook pending installation.
    /// @param permissions The submitted hook permissions.
    /// @param validAt The timestamp when the update can be accepted.
    event SetMarketHookSubmitted(Id indexed id, address indexed hook, uint256 permissions, uint64 validAt);

    /// @notice Emitted when a borrower's repay-cooldown exemption is submitted.
    /// @param account The borrower pending exemption.
    /// @param validAt The timestamp when the exemption can be accepted.
    event SetBorrowCooldownExemptSubmitted(address indexed account, uint64 validAt);

    /// @notice Emitted when transferring Lotus ownership is submitted.
    /// @param newOwner The pending Lotus owner.
    /// @param validAt The timestamp when the transfer can be accepted.
    event TransferLotusOwnershipSubmitted(address indexed newOwner, uint64 validAt);

    /// @notice Emitted when transferring governor ownership is submitted.
    /// @param newOwner The pending governor owner.
    /// @param validAt The timestamp when the transfer can be accepted.
    event TransferGovernorOwnershipSubmitted(address indexed newOwner, uint64 validAt);

    /// @notice Emitted when a guardian update is submitted.
    /// @param newGuardian The pending guardian.
    /// @param validAt The timestamp when the update can be accepted.
    event SetGuardianSubmitted(address indexed newGuardian, uint64 validAt);

    /// @notice Emitted when a module upgrade is submitted.
    /// @param module The module pending upgrade.
    /// @param newImplementation The submitted implementation.
    /// @param data Initialization or migration calldata committed by the submission.
    /// @param dataHash The hash checked again when the upgrade is accepted.
    /// @param validAt The timestamp when the upgrade can be accepted.
    event ModuleUpgradeSubmitted(
        address indexed module, address indexed newImplementation, bytes data, bytes32 dataHash, uint64 validAt
    );

    /// @notice Emitted when a module ownership transfer is submitted.
    /// @param module The module whose owner is being changed.
    /// @param newOwner The submitted module owner.
    /// @param validAt The timestamp when the transfer can be accepted.
    event TransferModuleOwnershipSubmitted(address indexed module, address indexed newOwner, uint64 validAt);

    /* REVOKE EVENTS */

    /// @notice Emitted when a pending fee update is cancelled.
    /// @param id The market whose pending tranche fee update was cancelled.
    /// @param trancheIndex The tranche whose pending fee update was cancelled.
    /// @param caller The owner or guardian that cancelled the update.
    event SetFeeRevoked(Id indexed id, uint256 indexed trancheIndex, address indexed caller);

    /// @notice Emitted when a pending fee-recipient update is cancelled.
    /// @param caller The owner or guardian that cancelled the update.
    event SetFeeRecipientRevoked(address indexed caller);

    /// @notice Emitted when a pending flash-loan fee update is cancelled.
    /// @param token The token whose pending fee update was cancelled.
    /// @param caller The owner or guardian that cancelled the update.
    event SetFlashLoanFeeRevoked(address indexed token, address indexed caller);

    /// @notice Emitted when a pending borrow LTV buffer update is cancelled.
    /// @param caller The owner or guardian that cancelled the update.
    event SetBorrowLtvBufferRevoked(address indexed caller);

    /// @notice Emitted when a pending risk-engine enablement is cancelled.
    /// @param riskEngine The risk engine whose pending enablement was cancelled.
    /// @param caller The owner or guardian that cancelled the enablement.
    event EnableRiskEngineRevoked(address indexed riskEngine, address indexed caller);

    /// @notice Emitted when a pending LLTV enablement is cancelled.
    /// @param lltv The LLTV whose pending enablement was cancelled.
    /// @param caller The owner or guardian that cancelled the enablement.
    event EnableLltvRevoked(uint128 indexed lltv, address indexed caller);

    /// @notice Emitted when a pending liquidation-module enablement is cancelled.
    /// @param module The module whose pending enablement was cancelled.
    /// @param caller The owner or guardian that cancelled the enablement.
    event EnableLiquidationModuleRevoked(address indexed module, address indexed caller);

    /// @notice Emitted when a pending module-manager enablement is cancelled.
    /// @param manager The manager whose pending enablement was cancelled.
    /// @param caller The owner or guardian that cancelled the enablement.
    event EnableModuleManagerRevoked(address indexed manager, address indexed caller);

    /// @notice Emitted when a pending market-hook update is cancelled.
    /// @param id The market whose pending hook update was cancelled.
    /// @param caller The owner or guardian that cancelled the update.
    event SetMarketHookRevoked(Id indexed id, address indexed caller);

    /// @notice Emitted when a pending repay-cooldown exemption is cancelled.
    /// @param account The borrower whose pending exemption was cancelled.
    /// @param caller The owner or guardian that cancelled the exemption.
    event SetBorrowCooldownExemptRevoked(address indexed account, address indexed caller);

    /// @notice Emitted when a pending Lotus ownership transfer is cancelled.
    /// @param caller The owner or guardian that cancelled the transfer.
    event TransferLotusOwnershipRevoked(address indexed caller);

    /// @notice Emitted when a pending governor ownership transfer is cancelled.
    /// @param caller The guardian that cancelled the transfer.
    event TransferGovernorOwnershipRevoked(address indexed caller);

    /// @notice Emitted when a pending guardian update is cancelled.
    /// @param caller The owner or guardian that cancelled the update.
    event SetGuardianRevoked(address indexed caller);

    /// @notice Emitted when a pending module upgrade is cancelled.
    /// @param module The module whose pending upgrade was cancelled.
    /// @param caller The owner or guardian that cancelled the upgrade.
    event ModuleUpgradeRevoked(address indexed module, address indexed caller);

    /// @notice Emitted when a pending module ownership transfer is cancelled.
    /// @param module The module whose pending transfer was cancelled.
    /// @param caller The owner or guardian that cancelled the transfer.
    event TransferModuleOwnershipRevoked(address indexed module, address indexed caller);

    /* ACCEPT EVENTS */

    /// @notice Emitted when a pending tranche fee update is accepted.
    /// @param id The market whose tranche fee was updated.
    /// @param trancheIndex The index of the tranche whose fee was updated.
    /// @param newFee The accepted tranche fee.
    event SetFeeAccepted(Id indexed id, uint256 indexed trancheIndex, uint64 newFee);

    /// @notice Emitted when a pending fee-recipient update is accepted.
    /// @param newFeeRecipient The accepted protocol fee recipient.
    event SetFeeRecipientAccepted(address indexed newFeeRecipient);

    /// @notice Emitted when a pending flash-loan fee update is accepted.
    /// @param token The token whose flash-loan fee was updated.
    /// @param newFee The accepted flash-loan fee.
    event SetFlashLoanFeeAccepted(address indexed token, uint64 newFee);

    /// @notice Emitted when a pending borrow LTV buffer update is accepted.
    /// @param newBuffer The accepted borrow LTV buffer.
    event SetBorrowLtvBufferAccepted(uint64 newBuffer);

    /// @notice Emitted when a pending risk-engine enablement is accepted.
    /// @param riskEngine The risk engine that was enabled.
    event EnableRiskEngineAccepted(address indexed riskEngine);

    /// @notice Emitted when a pending LLTV enablement is accepted.
    /// @param lltv The liquidation loan-to-value threshold that was enabled.
    event EnableLltvAccepted(uint128 indexed lltv);

    /// @notice Emitted when a pending liquidation-module enablement is accepted.
    /// @param module The liquidation module that was enabled.
    event EnableLiquidationModuleAccepted(address indexed module);

    /// @notice Emitted when a pending module-manager enablement is accepted.
    /// @param manager The module manager that was enabled.
    event EnableModuleManagerAccepted(address indexed manager);

    /// @notice Emitted when a pending market-hook update is accepted.
    /// @param id The market whose hook was updated.
    /// @param hook The accepted market hook.
    /// @param permissions The accepted hook permissions bitmap.
    event SetMarketHookAccepted(Id indexed id, address indexed hook, uint256 permissions);

    /// @notice Emitted when a pending repay-cooldown exemption is accepted.
    /// @param account The borrower that was exempted.
    event SetBorrowCooldownExemptAccepted(address indexed account);

    /// @notice Emitted when a pending Lotus ownership transfer is accepted.
    /// @param newOwner The address installed as Lotus's pending owner after the timelocked transfer is accepted.
    event TransferLotusOwnershipAccepted(address indexed newOwner);

    /// @notice Emitted when a pending module upgrade is accepted.
    /// @param module The module whose upgrade was accepted.
    /// @param newImplementation The accepted module implementation.
    /// @param dataHash The hash of the calldata executed during the upgrade.
    event ModuleUpgradeAccepted(address indexed module, address indexed newImplementation, bytes32 dataHash);

    /// @notice Emitted when a pending module ownership transfer is accepted.
    /// @param module The module whose ownership transfer was accepted.
    /// @param newOwner The address installed as the module's pending owner after the timelocked transfer is accepted.
    event TransferModuleOwnershipAccepted(address indexed module, address indexed newOwner);

    /// @notice Emitted when governor ownership is transferred.
    /// @param newOwner The new governor owner.
    event GovernorOwnerUpdated(address indexed newOwner);

    /// @notice Emitted when the guardian is updated.
    /// @param newGuardian The new guardian.
    event GuardianUpdated(address indexed newGuardian);

    /* VIEW FUNCTIONS */

    /// @return The minimum permitted standard timelock, in seconds.
    function MIN_TIMELOCK() external view returns (uint256);

    /// @return The minimum permitted long timelock, in seconds.
    function MIN_LONG_TIMELOCK() external view returns (uint256);

    /// @return The Lotus protocol governed by this contract.
    function LOTUS() external view returns (ILotus);

    /// @return The standard timelock for 24-hour governance actions, in seconds.
    function TIMELOCK() external view returns (uint256);

    /// @return The long timelock for ownership, guardian, and upgrade actions, in seconds.
    function LONG_TIMELOCK() external view returns (uint256);

    /// @return The current governor owner.
    function owner() external view returns (address);

    /// @return The guardian allowed to revoke pending actions.
    function guardian() external view returns (address);

    /* INSTANT RISK-REDUCING FUNCTIONS */

    /// @notice Lowers a tranche fee instantly. Reverts if newFee >= current fee.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The tranche whose fee is lowered.
    /// @param newFee The lower fee to set.
    /// @param riskEngineData Risk engine data used to accrue interest before mutation.
    function setFee(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        uint64 newFee,
        bytes calldata riskEngineData
    ) external;

    /// @notice Lowers a flash loan fee instantly. Reverts if newFee >= current fee.
    /// @param token The token whose flash-loan fee is being lowered.
    /// @param newFee The lower flash-loan fee to set.
    function setFlashLoanFee(address token, uint64 newFee) external;

    /// @notice Raises the global borrow LTV buffer instantly (risk-reducing). Reverts if newBuffer <= current buffer.
    /// @param newBuffer The higher borrow LTV buffer to set.
    function setBorrowLtvBuffer(uint64 newBuffer) external;

    /// @notice Disables a module manager instantly (risk-reducing).
    /// @param manager The module manager to disable.
    function disableModuleManager(address manager) external;

    /// @notice Pauses or unpauses Lotus operations. No timelock - emergency action.
    /// @dev Owner-only. Pause is risk-reducing; unpause flips the state instantly through this same
    /// function (no timelock) so the owner can lift an emergency without waiting. If a slower
    /// unpause flow is later required, add a timelocked variant alongside this.
    /// @param marketParams The market parameters (ignored when `global` is true).
    /// @param global Whether to set the global-pause flag (true) or the per-market flag (false).
    /// @param paused The new pause state.
    function setPaused(MarketParams memory marketParams, bool global, bool paused) external;

    /// @notice Clears a tranche's borrow cooldown instantly; cooldowns self-expire within `MIN_BORROW_DURATION`.
    /// @param id The market id.
    /// @param trancheIndex The tranche to clear.
    function clearBorrowCooldown(Id id, uint256 trancheIndex) external;

    /// @notice Removes a borrower's repay-cooldown exemption instantly. Reverts if `exempt` is true.
    /// @param account The borrower.
    /// @param exempt Must be false; granting goes through `submitSetBorrowCooldownExempt`.
    function setBorrowCooldownExempt(address account, bool exempt) external;

    /* 24H TIMELOCKED: FEE */

    /// @notice Submits a timelocked tranche fee update.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The tranche whose fee update is submitted.
    /// @param newFee The submitted fee.
    /// @param riskEngineData Risk engine data used to accrue interest before accepting.
    function submitSetFee(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        uint64 newFee,
        bytes calldata riskEngineData
    ) external;

    /// @notice Accepts a submitted tranche fee update after the standard timelock.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The tranche whose submitted fee update is accepted.
    /// @param riskEngineData Risk engine data used to accrue interest before mutation.
    function acceptSetFee(MarketParams memory marketParams, uint256 trancheIndex, bytes calldata riskEngineData)
        external;

    /// @notice Cancels a pending tranche fee update.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The tranche whose pending fee update is cancelled.
    function revokeSetFee(MarketParams memory marketParams, uint256 trancheIndex) external;

    /* 24H TIMELOCKED: FEE RECIPIENT */

    /// @notice Submits a timelocked fee-recipient update.
    /// @param newFeeRecipient The submitted fee recipient.
    function submitSetFeeRecipient(address newFeeRecipient) external;

    /// @notice Accepts a submitted fee-recipient update after the standard timelock.
    function acceptSetFeeRecipient() external;

    /// @notice Cancels a pending fee-recipient update.
    function revokeSetFeeRecipient() external;

    /* 24H TIMELOCKED: FLASH LOAN FEE */

    /// @notice Submits a timelocked flash-loan fee update.
    /// @param token The token whose flash-loan fee is being changed.
    /// @param newFee The submitted flash-loan fee.
    function submitSetFlashLoanFee(address token, uint64 newFee) external;

    /// @notice Accepts a submitted flash-loan fee update after the standard timelock.
    /// @param token The token whose flash-loan fee is being changed.
    function acceptSetFlashLoanFee(address token) external;

    /// @notice Cancels a pending flash-loan fee update.
    /// @param token The token whose pending fee update is cancelled.
    function revokeSetFlashLoanFee(address token) external;

    /// @notice Submits a timelocked borrow LTV buffer update (lowering the buffer is risk-increasing).
    /// @param newBuffer The submitted borrow LTV buffer.
    function submitSetBorrowLtvBuffer(uint64 newBuffer) external;

    /// @notice Accepts a submitted borrow LTV buffer update after the standard timelock.
    function acceptSetBorrowLtvBuffer() external;

    /// @notice Cancels a pending borrow LTV buffer update.
    function revokeSetBorrowLtvBuffer() external;

    /* 24H TIMELOCKED: ENABLE RISK ENGINE */

    /// @notice Submits a timelocked risk-engine enablement.
    /// @param riskEngine The risk engine to enable.
    function submitEnableRiskEngine(address riskEngine) external;

    /// @notice Accepts a submitted risk-engine enablement after the standard timelock.
    /// @param riskEngine The risk engine to enable.
    function acceptEnableRiskEngine(address riskEngine) external;

    /// @notice Cancels a pending risk-engine enablement.
    /// @param riskEngine The risk engine whose pending enablement is cancelled.
    function revokeEnableRiskEngine(address riskEngine) external;

    /* 24H TIMELOCKED: ENABLE LLTV */

    /// @notice Submits a timelocked LLTV enablement.
    /// @param lltv The LLTV to enable.
    function submitEnableLltv(uint128 lltv) external;

    /// @notice Accepts a submitted LLTV enablement after the standard timelock.
    /// @param lltv The LLTV to enable.
    function acceptEnableLltv(uint128 lltv) external;

    /// @notice Cancels a pending LLTV enablement.
    /// @param lltv The LLTV whose pending enablement is cancelled.
    function revokeEnableLltv(uint128 lltv) external;

    /* 24H TIMELOCKED: ENABLE LIQUIDATION MODULE */

    /// @notice Submits a timelocked liquidation-module enablement.
    /// @param liquidationModule The liquidation module to enable.
    function submitEnableLiquidationModule(address liquidationModule) external;

    /// @notice Accepts a submitted liquidation-module enablement after the standard timelock.
    /// @param liquidationModule The liquidation module to enable.
    function acceptEnableLiquidationModule(address liquidationModule) external;

    /// @notice Cancels a pending liquidation-module enablement.
    /// @param liquidationModule The module whose pending enablement is cancelled.
    function revokeEnableLiquidationModule(address liquidationModule) external;

    /* 24H TIMELOCKED: ENABLE MODULE MANAGER */

    /// @notice Submits a timelocked module-manager enablement.
    /// @param manager The module manager to enable.
    function submitEnableModuleManager(address manager) external;

    /// @notice Accepts a submitted module-manager enablement after the standard timelock.
    /// @param manager The module manager to enable.
    function acceptEnableModuleManager(address manager) external;

    /// @notice Cancels a pending module-manager enablement.
    /// @param manager The manager whose pending enablement is cancelled.
    function revokeEnableModuleManager(address manager) external;

    /* 24H TIMELOCKED: SET MARKET HOOK */

    /// @notice Submits a timelocked market-hook update.
    /// @param marketParams The market parameters.
    /// @param hook The hook to install.
    /// @param permissions The hook permissions to set.
    function submitSetMarketHook(MarketParams memory marketParams, address hook, uint256 permissions) external;

    /// @notice Accepts a submitted market-hook update after the standard timelock.
    /// @param marketParams The market parameters.
    function acceptSetMarketHook(MarketParams memory marketParams) external;

    /// @notice Cancels a pending market-hook update.
    /// @param marketParams The market parameters.
    function revokeSetMarketHook(MarketParams memory marketParams) external;

    /* 24H TIMELOCKED: BORROW COOLDOWN EXEMPTION */

    /// @notice Submits a timelocked repay-cooldown exemption for a borrower.
    /// @param account The borrower to exempt.
    function submitSetBorrowCooldownExempt(address account) external;

    /// @notice Accepts a submitted repay-cooldown exemption after the standard timelock.
    /// @param account The borrower to exempt.
    function acceptSetBorrowCooldownExempt(address account) external;

    /// @notice Cancels a pending repay-cooldown exemption.
    /// @param account The borrower whose pending exemption is cancelled.
    function revokeSetBorrowCooldownExempt(address account) external;

    /* 72H TIMELOCKED: LOTUS OWNERSHIP TRANSFER */

    /// @notice Submits a timelocked Lotus ownership transfer.
    /// @param newOwner The pending Lotus owner.
    function submitTransferLotusOwnership(address newOwner) external;

    /// @notice Accepts a submitted Lotus ownership transfer after the long timelock, starting Lotus's two-step handover.
    function acceptTransferLotusOwnership() external;

    /// @notice Completes Lotus's two-step handover when this governor is the incoming Lotus owner.
    function acceptLotusOwnership() external;

    /// @notice Cancels a pending Lotus ownership transfer.
    function revokeTransferLotusOwnership() external;

    /* 72H TIMELOCKED: GOVERNOR OWNERSHIP TRANSFER (2-STEP) */

    /// @notice Submits a timelocked governor ownership transfer.
    /// @param newOwner The pending governor owner.
    function submitTransferGovernorOwnership(address newOwner) external;

    /// @notice Accepts governor ownership after the long timelock.
    function acceptTransferGovernorOwnership() external;

    /// @notice Cancels a pending governor ownership transfer. Guardian only.
    function revokeTransferGovernorOwnership() external;

    /* 72H TIMELOCKED: GUARDIAN CHANGE */

    /// @notice Submits a timelocked guardian update.
    /// @param newGuardian The pending guardian.
    function submitSetGuardian(address newGuardian) external;

    /// @notice Accepts a submitted guardian update after the long timelock.
    function acceptSetGuardian() external;

    /// @notice Cancels a pending guardian update.
    function revokeSetGuardian() external;

    /* 72H TIMELOCKED: MODULE UPGRADES */

    /// @notice Submits a timelocked module upgrade.
    /// @param module The module to upgrade.
    /// @param newImplementation The submitted implementation.
    /// @param data Initialization or migration calldata used for validation and acceptance.
    function submitModuleUpgrade(address module, address newImplementation, bytes calldata data) external;

    /// @notice Accepts a submitted module upgrade after the long timelock.
    /// @param module The module to upgrade.
    /// @param data The calldata that must match the submitted data hash.
    function acceptModuleUpgrade(address module, bytes calldata data) external;

    /// @notice Cancels a pending module upgrade.
    /// @param module The module whose pending upgrade is cancelled.
    function revokeModuleUpgrade(address module) external;

    /* 72H TIMELOCKED: MODULE OWNERSHIP TRANSFER (2-STEP) */

    /// @notice Submits a timelocked module ownership transfer.
    /// @param module The module whose ownership is being transferred.
    /// @param newOwner The pending module owner.
    function submitTransferModuleOwnership(address module, address newOwner) external;

    /// @notice Accepts a submitted module ownership transfer after the long timelock.
    /// @param module The module whose ownership transfer is accepted.
    function acceptTransferModuleOwnership(address module) external;

    /// @notice Cancels a pending module ownership transfer.
    /// @param module The module whose pending transfer is cancelled.
    function revokeTransferModuleOwnership(address module) external;

    /// @notice Accepts pending ownership of a module (Ownable2Step second step).
    /// @dev Call this after an external party has called transferOwnership(address(governor)) on the module.
    /// @param module The module whose pending ownership should be accepted.
    function acceptModuleOwnership(address module) external;
}

src/interfaces/ILotus.sol

// SPDX-License-Identifier: MIT
// Adapted in part from Morpho Blue, Copyright (c) 2023-2026 Morpho Association, MIT License.
pragma solidity ^0.8.28;

import {IRiskEngine} from "./IRiskEngine.sol";
import {ITwoStepOwnable} from "../access/TwoStepOwnable.sol";

type Id is bytes32;

/// @notice Core market parameters shared across all tranches.
struct MarketParams {
    /// @notice Loan token shared across all tranches.
    address loanToken;
    /// @notice Risk engine for the market, shared across all tranches.
    address riskEngine;
    /// @notice Liquidation module for the market, shared across all tranches.
    address liquidationModule;
    /// @notice keccak256 hash of abi-encoded TrancheConfig array.
    bytes32 trancheConfigsHash;
}

/// @notice Per-tranche configuration stored separately from core params.
struct TrancheConfig {
    /// @notice Collateral token accepted by this tranche.
    address collateralToken;
    /// @notice Oracle used to price this tranche's collateral token.
    address oracle;
    /// @notice Liquidation loan-to-value threshold for this tranche, in wad.
    uint128 lltv;
}

/// @notice Per-tranche user position state.
/// @dev Warning: The `supplyShares` for the protocol `feeRecipient` is accurate as of the last interest accrual.
struct Position {
    /// @notice Supply shares for this tranche.
    uint256 supplyShares;
    /// @notice Borrow shares for this tranche.
    uint128 borrowShares;
    /// @notice Collateral amount for this tranche.
    uint128 collateral;
    /// @notice Size-weighted timestamp of this position's outstanding borrow.
    uint64 borrowTs;
}

/// @notice Aggregate accounting state for one market tranche.
/// @dev Warning: The `supplyAssets` and `borrowAssets` are accurate as of the last interest accrual.
/// @dev Warning: The `supplyShares` does not include supply shares to be issued to the `feeRecipient` during the next
/// interest accrual.
/// @dev `supplyShares` is `uint256`: bad debt reduces `supplyAssets` without reducing `supplyShares`, so a wiped
/// tranche's collapsed share price can mint far more than `uint128` shares. Asset fields stay `uint128` because they
/// only ever hold real token amounts. Layout (3 slots): `supplyAssets | fee | lastUpdate`, `supplyShares`,
/// `borrowAssets | borrowShares`, so supply, borrow and accrual each write at most two slots per tranche.
struct Tranche {
    /// @notice Total amount of assets supplied at this tranche.
    uint128 supplyAssets;
    /// @notice Protocol fee taken from interest accrued at this tranche.
    uint64 fee;
    /// @notice Last timestamp when interest was accrued for this tranche.
    uint64 lastUpdate;
    /// @notice Total supply shares for this tranche.
    uint256 supplyShares;
    /// @notice Total borrow assets for only the current tranche.
    uint128 borrowAssets;
    /// @notice Total borrow shares for only the current tranche.
    uint128 borrowShares;
}

/// @notice EIP-712 authorization payload.
struct Authorization {
    /// @notice Account granting or revoking authorization.
    address authorizer;
    /// @notice Account receiving or losing authorization.
    address authorized;
    /// @notice Whether authorization is granted or revoked.
    bool isAuthorized;
    /// @notice Authorizer nonce consumed by this payload.
    uint256 nonce;
    /// @notice Timestamp after which the signature is invalid.
    uint256 deadline;
}

/// @notice ECDSA signature fields for EIP-712 authorization payloads.
struct Signature {
    /// @notice ECDSA recovery id.
    uint8 v;
    /// @notice ECDSA r value.
    bytes32 r;
    /// @notice ECDSA s value.
    bytes32 s;
}

/// @title ILotus
/// @notice Interface for the Lotus core lending protocol.
interface ILotus is ITwoStepOwnable {
    /// @notice Emitted when the protocol is globally paused.
    event GlobalPaused();

    /// @notice Emitted when the protocol is globally unpaused.
    /// @param unpausedAt The timestamp at which the global pause was released.
    event GlobalUnpaused(uint64 unpausedAt);

    /// @notice Emitted when a single market is paused.
    /// @param id The market id.
    event MarketPaused(Id indexed id);

    /// @notice Emitted when a single market is unpaused.
    /// @param id The market id.
    event MarketUnpaused(Id indexed id);

    /// @notice Emitted when a token's flash loan fee is updated.
    /// @param token The token whose flash loan fee was updated.
    /// @param newFee The new flash loan fee in WAD.
    event FlashLoanFeeUpdated(address indexed token, uint64 newFee);

    /// @notice Emitted when an LLTV is enabled.
    /// @param lltv The enabled liquidation LTV ratio.
    event LltvEnabled(uint256 indexed lltv);

    /// @notice Emitted after aggregate accounting state changes for a tranche.
    /// @param id The market id.
    /// @param trancheIndex The tranche index.
    /// @param supplyAssets Total supplied assets after the change.
    /// @param supplyShares Total supply shares after the change.
    /// @param borrowAssets Total borrowed assets after the change.
    /// @param borrowShares Total borrow shares after the change.
    event TrancheStateUpdated(
        Id indexed id,
        uint256 indexed trancheIndex,
        uint256 supplyAssets,
        uint256 supplyShares,
        uint256 borrowAssets,
        uint256 borrowShares
    );

    /// @notice Emitted when interest is added to a tranche's aggregate borrow balance.
    /// @param id The market id.
    /// @param trancheIndex The tranche index.
    /// @param borrowInterest The amount added to aggregate borrow assets.
    event BorrowInterestAccrued(Id indexed id, uint256 indexed trancheIndex, uint256 borrowInterest);

    /// @notice Emitted when interest is distributed to a tranche's suppliers.
    /// @param id The market id.
    /// @param trancheIndex The tranche index.
    /// @param supplyInterest The amount added to aggregate supply assets.
    /// @param feeShares The supply shares minted to the protocol fee recipient.
    event SupplyInterestDistributed(
        Id indexed id, uint256 indexed trancheIndex, uint256 supplyInterest, uint256 feeShares
    );

    /// @notice Emitted when bad debt is allocated to a tranche's suppliers.
    /// @param id The market id.
    /// @param originTrancheIndex The tranche where the defaulted borrow position originated.
    /// @param absorbingTrancheIndex The tranche whose aggregate supply assets absorb the loss.
    /// @param assetsReduced The amount removed from the absorbing tranche's supply assets.
    event BadDebtAllocated(
        Id indexed id, uint256 indexed originTrancheIndex, uint256 indexed absorbingTrancheIndex, uint256 assetsReduced
    );

    /// @notice Emitted when a bad-debt event arms the borrow cooldown on the tranches junior to its origin.
    /// @param id The market id.
    /// @param originTrancheIndex The tranche where the bad debt originated.
    /// @param cooldownUntil Latest resulting expiry among the affected junior tranches, or the event's own expiry
    /// if there are no junior tranches. Each tranche accumulates its own remaining window, capped at
    /// `MIN_BORROW_DURATION` from now.
    event BorrowCooldownArmed(Id indexed id, uint256 indexed originTrancheIndex, uint64 cooldownUntil);

    /// @notice Emitted when the owner clears a tranche's borrow cooldown.
    /// @param id The market id.
    /// @param trancheIndex The tranche whose cooldown was cleared.
    event BorrowCooldownCleared(Id indexed id, uint256 indexed trancheIndex);

    /// @notice Emitted when the owner sets a borrower's exemption from the repay cooldown.
    /// @param account The borrower.
    /// @param exempt Whether `account` is exempt.
    event BorrowCooldownExemptSet(address indexed account, bool exempt);

    /// @return domainSeparator The EIP-712 domain separator for Lotus.
    function DOMAIN_SEPARATOR() external view returns (bytes32 domainSeparator);

    /// @notice Minimum size-weighted age a borrow position needs to be repaid while its tranche's cooldown is armed.
    function MIN_BORROW_DURATION() external view returns (uint256);

    /// @notice Bad debt, as a WAD fraction of cascade supply, at which the borrow cooldown arms for the full duration.
    function FULL_COOLDOWN_BAD_DEBT_RATIO() external view returns (uint256);

    /* OWNER FUNCTIONS */

    /// @notice The Lotus fee recipient for all markets, tranches, and flash loans.
    /// @dev The `feeRecipient` receives tranche fees during interest accrual via supply shares.
    /// @return recipient The protocol fee recipient.
    function feeRecipient() external view returns (address recipient);

    /// @notice Global relative buffer below each tranche's LLTV that caps new borrows and collateral withdrawals.
    /// @dev `borrow` and `withdrawCollateral` require the position to stay within `lltv * (WAD - borrowLtvBuffer) / WAD`.
    /// Liquidation eligibility and every other health computation keep using the plain LLTV, so a fresh position
    /// cannot become liquidatable through interest alone until its debt grows past the buffer.
    /// @return buffer The buffer in WAD, in [`MIN_BORROW_LTV_BUFFER`, `MAX_BORROW_LTV_BUFFER`].
    function borrowLtvBuffer() external view returns (uint64 buffer);

    /// @notice The Lotus flash loan fee for `token`, in WAD.
    /// @param token The token to quote the configured flash loan fee for.
    /// @return fee The flash loan fee rate applied to `token`.
    function flashLoanFee(address token) external view returns (uint64 fee);

    /// @notice Sets the protocol interest fee for a specific tranche in a market.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The index of the tranche to set the fee for.
    /// @param newFee The new fee to set.
    /// @param riskEngineData The risk engine data to pass during interest accrual.
    function setFee(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        uint64 newFee,
        bytes calldata riskEngineData
    ) external;

    /// @notice Sets the Lotus fee recipient.
    /// @param newFeeRecipient The new Lotus fee recipient.
    function setFeeRecipient(address newFeeRecipient) external;

    /// @notice Sets the Lotus flash loan fee for `token`.
    /// @param token The token to configure the flash loan fee for.
    /// @param newFee The new flash loan fee, in WAD.
    function setFlashLoanFee(address token, uint64 newFee) external;

    /// @notice Sets the global borrow LTV buffer.
    /// @dev Reverts if `newBuffer` equals the current buffer or is outside
    /// [`MIN_BORROW_LTV_BUFFER`, `MAX_BORROW_LTV_BUFFER`].
    /// @param newBuffer The new relative buffer below each tranche's LLTV, in WAD.
    function setBorrowLtvBuffer(uint64 newBuffer) external;

    /// @notice Enables `riskEngine` for Lotus markets.
    /// @param riskEngine The risk engine to enable.
    function enableRiskEngine(address riskEngine) external;

    /// @notice Enables `lltv` for Lotus markets.
    /// @param lltv The LLTV to enable.
    function enableLltv(uint128 lltv) external;

    /// @notice Enables `liquidationModule` for Lotus markets.
    /// @param liquidationModule The liquidation module to enable.
    function enableLiquidationModule(address liquidationModule) external;

    /// @notice Enables a module manager who can enable risk engines and liquidation modules.
    /// @param manager The module manager address.
    function enableModuleManager(address manager) external;

    /// @notice Disables a module manager.
    /// @param manager The module manager address.
    function disableModuleManager(address manager) external;

    /// @notice Sets or clears the market hook configuration.
    /// @param marketParams The market parameters (used to derive market id).
    /// @param hook The hook contract address (zero address to disable hooks).
    /// @param permissions The permissions bitmap indicating which hooks are implemented.
    function setMarketHook(MarketParams memory marketParams, address hook, uint256 permissions) external;

    /* PAUSE */

    /// @notice Pauses or unpauses state-changing operations. Owner only.
    /// @dev When `global` is true, applies to every market across the protocol and `marketParams`
    /// is ignored. When `global` is false, applies to the single market identified by
    /// `marketParams`; forbidden while globally paused. Unpausing (in either scope) records the
    /// moment so the lazy per-market sync skips interest accrual over the pause window.
    /// Interest from the last pre-pause interaction up to the pause is not captured by the lazy
    /// sync. Operators who need that interest realized must call `accrueInterest` before pausing;
    /// it cannot be recovered during a pause, because accrual reverts while paused, or after
    /// unpause, because the sync skips directly to the unpause timestamp. This preserves
    /// emergency-pause availability when accrual itself depends on a broken oracle or risk engine
    /// and could revert.
    /// @param marketParams The market parameters (ignored when `global` is true).
    /// @param global Whether to set the global-pause flag (true) or the per-market flag (false).
    /// @param paused The new pause state.
    function setPaused(MarketParams memory marketParams, bool global, bool paused) external;

    /// @notice Clears a tranche's borrow cooldown once no young borrow in it needs gating. Clear-only: never arms.
    /// @param id The market id.
    /// @param trancheIndex The tranche to clear.
    function clearBorrowCooldown(Id id, uint256 trancheIndex) external;

    /// @notice Exempts `account`'s positions from the repay cooldown, whoever calls repay on its behalf.
    /// @param account The borrower (repay's `onBehalf`).
    /// @param exempt Whether `account` is exempt.
    function setBorrowCooldownExempt(address account, bool exempt) external;

    /* MARKET CREATION */

    /// @notice Creates a new Lotus market.
    /// @dev Lotus settlement assumes exact token receipt on inbound transfers.
    /// @dev Do not configure fee-on-transfer or other transfer-shortfall loan or collateral tokens.
    /// @dev `marketParams.trancheConfigsHash` is recomputed from `tranches`, returned, and used as input into the
    /// market id calculation; any caller-supplied value is ignored.
    /// @param marketParams The core market parameters (loan token, risk engine, liquidation module).
    /// @param tranches The per-tranche configuration array.
    /// @param riskEngineParams The parameters for the risk engine.
    /// @param liquidationParams The parameters for the liquidation module.
    /// @return id The id of the created market (derived from the recomputed `marketParams`).
    /// @return trancheConfigsHash The tranche config hash recomputed from `tranches`.
    function createMarket(
        MarketParams memory marketParams,
        TrancheConfig[] memory tranches,
        bytes calldata riskEngineParams,
        bytes calldata liquidationParams
    ) external returns (Id id, bytes32 trancheConfigsHash);

    /* LENDER FUNCTIONS */

    /// @notice Supplies assets to a specific tranche in the market.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The index of the tranche to supply to.
    /// @param assets The amount of assets to supply (use 0 if supplying by shares).
    /// @param shares The amount of shares to supply (use 0 if supplying by assets).
    /// @param onBehalf The address to supply on behalf of.
    /// @param data Arbitrary data to pass to the callback (if any).
    /// @param riskEngineData The risk engine data to pass during interest accrual.
    /// @return suppliedAssets The actual amount of assets supplied.
    /// @return suppliedShares The actual amount of shares supplied.
    function supply(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        bytes calldata data,
        bytes calldata riskEngineData
    ) external returns (uint256 suppliedAssets, uint256 suppliedShares);

    /// @notice Withdraws assets from a specific tranche in the market.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The index of the tranche to withdraw from.
    /// @param assets The amount of assets to withdraw (use 0 if withdrawing by shares).
    /// @param shares The amount of shares to withdraw (use 0 if withdrawing by assets).
    /// @param onBehalf The address to withdraw on behalf of.
    /// @param receiver The address to send the withdrawn assets to.
    /// @param riskEngineData The risk engine data to pass during interest accrual.
    /// @return withdrawnAssets The actual amount of assets withdrawn.
    /// @return withdrawnShares The actual amount of shares withdrawn.
    function withdraw(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        address receiver,
        bytes calldata riskEngineData
    ) external returns (uint256 withdrawnAssets, uint256 withdrawnShares);

    /* BORROWER FUNCTIONS */

    /// @notice Borrows assets from a specific tranche in the market.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The index of the tranche to borrow from.
    /// @param assets The amount of assets to borrow (use 0 if borrowing by shares).
    /// @param shares The amount of shares to borrow (use 0 if borrowing by assets). A borrow by shares pays out the
    /// shares' value rounded down and mints only the shares that amount costs, which can be fewer than requested.
    /// @param onBehalf The address to borrow on behalf of.
    /// @param receiver The address to send the borrowed assets to.
    /// @param riskEngineData The risk engine data to pass during interest accrual.
    /// @return borrowedAssets The actual amount of assets borrowed.
    /// @return borrowedShares The actual amount of shares borrowed.
    function borrow(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        address receiver,
        bytes calldata riskEngineData
    ) external returns (uint256 borrowedAssets, uint256 borrowedShares);

    /// @notice Repays borrowed assets for a specific tranche in the market with callback support.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The index of the tranche to repay to.
    /// @param assets The amount of assets to repay (use 0 if repaying by shares).
    /// @param shares The amount of shares to repay (use 0 if repaying by assets). A partial repay by shares burns at
    /// least the shares its charged assets are worth, capped at the position, which can be more than requested.
    /// @param onBehalf The address to repay on behalf of.
    /// @param data Arbitrary data to pass to the callback (if any).
    /// @param riskEngineData The risk engine data to pass during interest accrual.
    /// @return repaidAssets The actual amount of assets repaid.
    /// @return repaidShares The actual amount of shares repaid.
    function repay(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        bytes calldata data,
        bytes calldata riskEngineData
    ) external returns (uint256 repaidAssets, uint256 repaidShares);

    /// @notice Supplies collateral to a specific tranche in the market with callback support.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The index of the tranche to supply collateral to.
    /// @param assets The amount of collateral assets to supply.
    /// @param onBehalf The address to supply collateral on behalf of.
    /// @param data Arbitrary data to pass to the callback (if any).
    function supplyCollateral(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        uint256 assets,
        address onBehalf,
        bytes calldata data
    ) external;

    /// @notice Withdraws collateral from a specific tranche in the market.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The index of the tranche to withdraw collateral from.
    /// @param assets The amount of collateral assets to withdraw.
    /// @param onBehalf The address to withdraw collateral on behalf of.
    /// @param receiver The address to send the withdrawn collateral to.
    /// @param riskEngineData The risk engine data to pass during interest accrual.
    function withdrawCollateral(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        uint256 assets,
        address onBehalf,
        address receiver,
        bytes calldata riskEngineData
    ) external;

    /* LIQUIDATION */

    /// @notice Liquidates a borrower's position.
    /// @dev The returned `repaidAssets` is computed with rounding up to favor protocol safety.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The tranche index of the position to liquidate.
    /// @param borrower The address of the borrower to liquidate.
    /// @param riskEngineData risk engine-specific data.
    /// @param callbackData Optional data forwarded to the liquidator callback.
    /// @param lmData Opaque liquidation-module data interpreted by the selected module.
    /// @return seizedAssets The collateral assets seized.
    /// @return repaidAssets The loan assets repaid by the liquidator.
    function liquidate(
        MarketParams memory marketParams,
        uint256 trancheIndex,
        address borrower,
        bytes calldata riskEngineData,
        bytes calldata callbackData,
        bytes calldata lmData
    ) external returns (uint256 seizedAssets, uint256 repaidAssets);

    /* INTEREST MANAGEMENT */

    /// @notice Accrues interest for all tranches in a market.
    /// @param marketParams The market parameters.
    /// @param riskEngineData The risk engine data to pass during interest accrual.
    function accrueInterest(MarketParams memory marketParams, bytes calldata riskEngineData) external;

    /* FLASH LOANS */

    /// @notice Returns the fee owed for borrowing `assets` of `token`.
    /// @param token The token to quote.
    /// @param assets The amount to flash loan.
    /// @return fee The flash loan fee owed on top of `assets`.
    function flashFee(address token, uint256 assets) external view returns (uint256 fee);

    /// @notice Executes a flash loan.
    /// @param token The address of the token to flash loan.
    /// @param assets The amount of assets to flash loan.
    /// @param data Arbitrary data to pass to the callback.
    function flashLoan(address token, uint256 assets, bytes calldata data) external;

    /* AUTHORIZATION */

    /// @notice Returns true if `authorized` can modify `authorizer`'s position on all markets/tranches.
    /// @param authorizer The account delegating permissions.
    /// @param authorized The account receiving delegated permissions.
    /// @return isAuthorized_ Whether `authorized` is currently approved.
    function isAuthorized(address authorizer, address authorized) external view returns (bool isAuthorized_);

    /// @notice The `authorizer`'s current nonce.
    /// @dev To prevent replay attacks with EIP-712 signatures.
    /// @param authorizer The account whose nonce is queried.
    /// @return currentNonce The current authorization nonce.
    function nonce(address authorizer) external view returns (uint256 currentNonce);

    /// @notice Sets `authorized` authorization to act on behalf of `msg.sender`.
    /// @param authorized The authorized address.
    /// @param newIsAuthorized The new authorization status.
    function setAuthorization(address authorized, bool newIsAuthorized) external;

    /// @notice Sets authorization via signature.
    /// @param authorization The authorization struct.
    /// @param signature The signature struct.
    function setAuthorizationWithSig(Authorization memory authorization, Signature calldata signature) external;

    /* VIEW FUNCTIONS */

    /// @notice Returns true if `riskEngine` is enabled for Lotus markets.
    /// @param riskEngine The risk engine to check.
    /// @return isEnabled Whether `riskEngine` is enabled.
    function isRiskEngineEnabled(address riskEngine) external view returns (bool isEnabled);

    /// @notice Returns true if `lltv` is enabled for Lotus markets.
    /// @param lltv The LLTV to check.
    /// @return isEnabled Whether `lltv` is enabled.
    function isLltvEnabled(uint256 lltv) external view returns (bool isEnabled);

    /// @notice Returns true if `liquidationModule` is enabled for Lotus markets.
    /// @param liquidationModule The liquidation module to check.
    /// @return isEnabled Whether `liquidationModule` is enabled.
    function isLiquidationModuleEnabled(address liquidationModule) external view returns (bool isEnabled);

    /// @notice Returns true if `manager` is a module manager.
    /// @param manager The address to check.
    /// @return Whether `manager` is a module manager.
    function isModuleManager(address manager) external view returns (bool);

    /// @notice Returns the last interest accrual time for a market.
    /// @param id The market id.
    /// @param trancheIndex The tranche index.
    /// @return timestamp The unix timestamp of last accrual for the tranche.
    function lastUpdate(Id id, uint256 trancheIndex) external view returns (uint64 timestamp);

    /// @notice Returns when a tranche's borrow cooldown lapses; while armed, only positions at least
    /// `MIN_BORROW_DURATION` old may repay.
    /// @param id The market id.
    /// @param trancheIndex The tranche index.
    /// @return The cooldown expiry timestamp, or zero if never armed.
    function borrowCooldownUntil(Id id, uint256 trancheIndex) external view returns (uint64);

    /// @notice Returns whether `account`'s positions skip the repay cooldown.
    /// @param account The borrower.
    function isBorrowCooldownExempt(address account) external view returns (bool);

    /// @notice Returns the market parameters for a given market id.
    /// @param id The market id.
    /// @return The MarketParams struct for the market.
    function getMarketParams(Id id) external view returns (MarketParams memory);

    /// @notice Returns the tranche config for a given market id and tranche index.
    /// @param id The market id.
    /// @param trancheIndex The tranche index.
    /// @return The TrancheConfig struct for the tranche.
    function getTrancheConfig(Id id, uint256 trancheIndex) external view returns (TrancheConfig memory);

    /// @notice Returns all tranche configs for a given market id.
    /// @param id The market id.
    /// @return An array of TrancheConfig structs for the market.
    function getTrancheConfigs(Id id) external view returns (TrancheConfig[] memory);

    /// @notice Returns the tranches for a given market id.
    /// @param id The market id.
    /// @return An array of Tranche structs for the market.
    function getMarketTranches(Id id) external view returns (Tranche[] memory);

    /// @notice Returns a single tranche for a given market id and tranche index.
    /// @param id The market id.
    /// @param trancheIndex The tranche index.
    /// @return The Tranche struct for the tranche.
    function getMarketTranche(Id id, uint256 trancheIndex) external view returns (Tranche memory);

    /// @notice Returns the number of tranches for a given market id.
    /// @param id The market id.
    /// @return The number of tranches in the market.
    function getNumMarketTranches(Id id) external view returns (uint256);

    /// @notice Returns the effective pause state for a market, as the interest-accrual gate sees it.
    /// @dev Lets off-chain valuation mirror accrual: when `paused`, no interest accrues over the
    /// pause window; when `unpausedAt > syncedAt`, the next accrual restarts each tranche from
    /// `unpausedAt` rather than its stale pre-pause `lastUpdate`.
    /// @param id The market id.
    /// @return paused Whether the protocol or this market is currently paused.
    /// @return unpausedAt The most recent unpause timestamp relevant to this market (global or per-market).
    /// @return syncedAt The unpause timestamp already synchronized into this market's tranche `lastUpdate` values.
    function getMarketPauseState(Id id) external view returns (bool paused, uint64 unpausedAt, uint64 syncedAt);

    /// @notice Returns the risk engine for a given market id.
    /// @param id The market id.
    /// @return The IRiskEngine contract for the market.
    function getMarketRiskEngine(Id id) external view returns (IRiskEngine);

    /// @notice Returns a user's position in a specific market tranche.
    /// @param id The market id.
    /// @param user The address of the user.
    /// @param trancheIndex The tranche index.
    /// @return The Position struct for the user in the tranche.
    function getPosition(Id id, address user, uint256 trancheIndex) external view returns (Position memory);

    /// @notice Returns the current borrowed assets and max borrowable assets for a borrower in a market tranche.
    /// @dev Accurate as of the last interest accrual.
    /// @dev Use `accrueInterest` first (or a lens helper) when post-accrual values are required.
    /// @param marketParams The market parameters.
    /// @param trancheIndex The tranche index.
    /// @param borrower The borrower account.
    /// @return borrowed The current borrowed assets in the tranche.
    /// @return maxBorrow The current max borrowable assets in the tranche.
    function getMaxBorrowAndBorrowed(MarketParams memory marketParams, uint256 trancheIndex, address borrower)
        external
        view
        returns (uint256 borrowed, uint256 maxBorrow);

    /// @notice Computes junior supply for a given market and tranche.
    /// @dev Accurate as of the last interest accrual.
    /// @param id The market whose junior supply is computed.
    /// @param trancheIndex The tranche whose junior supply is computed.
    /// @return The junior supply amount.
    function getJrSupply(Id id, uint256 trancheIndex) external view returns (uint256);

    /// @notice Returns risk engine-effective free supply available for withdraw or borrow.
    /// @dev Bounded by Lotus's current waterfall-backed physical ceiling and then refined by the market risk engine.
    /// @param id The market whose free supply is returned.
    /// @param trancheIndex The tranche whose free supply is returned.
    /// @return The free supply amount.
    function getFreeSupply(Id id, uint256 trancheIndex) external view returns (uint256);

    /// @notice Returns risk engine-effective free supply available for withdraw or borrow.
    /// @dev Bounded by Lotus's current waterfall-backed physical ceiling and then refined by the market risk engine.
    /// @param id The market whose free supply is returned.
    /// @param trancheIndex The tranche whose free supply is returned.
    /// @param riskEngineData Custom data to be passed to the risk engine implementation.
    /// @return The free supply amount.
    function getFreeSupply(Id id, uint256 trancheIndex, bytes calldata riskEngineData) external view returns (uint256);

    /// @notice Computes junior net supply for all tranches in a market.
    /// @dev Accurate as of the last interest accrual.
    /// @param id The market id.
    /// @return An array of junior net supply amounts for each tranche.
    function getJrNetSupply(Id id) external view returns (uint256[] memory);

    /// @notice Returns the market hook configuration (if any) for a given market id.
    /// @param id The market id.
    /// @return hook The hook contract address (zero address if disabled).
    /// @return permissions The hook permissions bitmap.
    function getMarketHookConfig(Id id) external view returns (address hook, uint256 permissions);
}

src/interfaces/IRiskEngine.sol

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

import {Id, Tranche} from "./ILotus.sol";

/// @notice Per-tranche accrual delta returned by cascade accrual.
struct AccrualDelta {
    /// @notice Interest added to `borrowAssets`.
    uint256 borrowInterest;
    /// @notice Interest added to `supplyAssets`.
    uint256 supplyInterest;
}

/// @notice Per-tranche bad debt reductions returned by the risk engine.
struct BadDebtDeltas {
    /// @notice Full-length array of supply asset reductions.
    uint256[] supplyReductions;
}

/// @title IRiskEngine
/// @notice The Risk Engine interface expected by Lotus protocol.
interface IRiskEngine {
    /// @notice Initializes the risk engine for a Lotus market.
    /// @param id The market id.
    /// @param riskEngineParams ABI-encoded params expected by the risk engine implementation.
    function initialize(Id id, bytes calldata riskEngineParams) external;

    /// @notice Accrues interest across all tranches with cascading distribution.
    /// @dev May update internal risk engine state (e.g. adaptive rates).
    /// @param id The market id.
    /// @param tranches The current tranche state array.
    /// @param riskEngineData Custom data to be passed to the risk engine implementation.
    /// @return deltas The per-tranche accrual deltas.
    /// @return freeSupply The risk-engine-effective withdraw/borrow liquidity across accrued tranches,
    /// bounded by Lotus's trusted physical `freeSupplyCap`.
    function accrueInterest(Id id, Tranche[] calldata tranches, bytes calldata riskEngineData)
        external
        returns (AccrualDelta[] memory deltas, uint256 freeSupply);

    /// @notice Returns the effective free supply at a tranche without accruing interest.
    /// @param id The market id.
    /// @param tranches The current tranche state array.
    /// @param trancheIndex The tranche index to query.
    /// @param riskEngineData Custom data to be passed to the risk engine implementation.
    /// @return freeSupply The risk-engine-effective withdraw/borrow liquidity at the tranche,
    /// bounded by Lotus's trusted physical `freeSupplyCap`.
    function getFreeSupply(Id id, Tranche[] calldata tranches, uint256 trancheIndex, bytes calldata riskEngineData)
        external
        view
        returns (uint256 freeSupply);

    /// @notice Distributes bad debt losses across tranches from originIndex upward.
    /// @param id The market id.
    /// @param tranches The current tranche state array.
    /// @param originTrancheIndex The tranche index where bad debt originated.
    /// @param badDebtAssets The amount of bad debt to distribute.
    /// @return deltas The per-tranche supply reductions after bad debt distribution.
    function distributeBadDebt(Id id, Tranche[] calldata tranches, uint256 originTrancheIndex, uint256 badDebtAssets)
        external
        pure
        returns (BadDebtDeltas memory deltas);

    /// @notice View-only preview of accrueInterest for off-chain estimation.
    /// @param id The market id.
    /// @param tranches The current tranche state array.
    /// @param riskEngineData Custom data to be passed to the risk engine implementation.
    /// @return deltas The preview per-tranche accrual deltas.
    /// @return freeSupply The risk-engine-effective withdraw/borrow liquidity across accrued tranches,
    /// bounded by Lotus's trusted physical `freeSupplyCap`.
    function previewAccrueInterest(Id id, Tranche[] calldata tranches, bytes calldata riskEngineData)
        external
        view
        returns (AccrualDelta[] memory deltas, uint256 freeSupply);

    /// @notice Validates that `riskEngineData` is well-formed for this engine before it is used or persisted.
    /// @dev Called on an integrating adapter's position write path so that a caller cannot associate arbitrary or
    /// oversized `riskEngineData` with a position (that data is later SLOADed and forwarded to the engine on every
    /// valuation read). Engines that ignore `riskEngineData` MUST reject any non-empty payload; engines with
    /// call-time config SHOULD validate its structure and bound its size. Reverts if the data is not acceptable.
    /// @param riskEngineData The custom data a caller wants associated with a position.
    function validateRiskEngineData(bytes calldata riskEngineData) external view;
}

src/libraries/MarketParamsLib.sol

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

import {Id, MarketParams, TrancheConfig} from "../interfaces/ILotus.sol";

/// @title MarketParamsLib
/// @notice Helpers for deriving and transforming Lotus market parameter structs.
library MarketParamsLib {
    /// @dev Computes the unique id for a given `MarketParams` struct.
    function id(MarketParams memory marketParams) internal pure returns (Id marketParamsId) {
        marketParamsId = Id.wrap(
            keccak256(
                abi.encode(
                    marketParams.loanToken,
                    marketParams.riskEngine,
                    marketParams.liquidationModule,
                    marketParams.trancheConfigsHash
                )
            )
        );
    }

    /// @dev Computes `trancheConfigsHash` from a tranche configuration array.
    function computeTrancheConfigsHash(TrancheConfig[] memory tranches) internal pure returns (bytes32) {
        // forge-lint: disable-next-item(asm-keccak256)
        return keccak256(abi.encode(tranches));
    }
}

src/libraries/PendingLib.sol

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

/// @title PendingLib
/// @notice Types and helpers for per-parameter timelocked pending values.
/// @dev A `validAt` of 0 means "no pending value". Non-zero means the value
///      becomes executable at `block.timestamp >= validAt`.
library PendingLib {
    /* TYPES */

    /// @notice Pending address value with an execution timestamp.
    struct PendingAddress {
        /// @notice The submitted address value.
        address value;
        /// @notice The timestamp when the value can be accepted, or zero when no value is pending.
        uint64 validAt;
    }

    /// @notice Pending uint64 value with an execution timestamp.
    struct PendingUint64 {
        /// @notice The submitted uint64 value.
        uint64 value;
        /// @notice The timestamp when the value can be accepted, or zero when no value is pending.
        uint64 validAt;
    }

    /// @notice Pending uint128 value with an execution timestamp.
    struct PendingUint128 {
        /// @notice The submitted uint128 value.
        uint128 value;
        /// @notice The timestamp when the value can be accepted, or zero when no value is pending.
        uint64 validAt;
    }

    /// @notice Pending market hook configuration with an execution timestamp.
    struct PendingMarketHook {
        /// @notice The submitted hook address.
        address hook;
        /// @notice The timestamp when the value can be accepted, or zero when no value is pending.
        uint64 validAt;
        /// @notice The submitted hook permissions bitmap.
        uint256 permissions;
    }

    /// @notice Pending UUPS implementation upgrade with an execution timestamp.
    struct PendingUpgrade {
        /// @notice The submitted implementation address.
        address newImplementation;
        /// @notice The timestamp when the value can be accepted, or zero when no value is pending.
        uint64 validAt;
        /// @notice The expected calldata hash supplied at acceptance.
        bytes32 dataHash;
    }

    /* ERRORS */

    /// @notice Timelocked action accepted before the delay has elapsed.
    /// @param validAt The timestamp when the pending value becomes executable.
    error TimelockNotExpired(uint64 validAt);

    /// @notice No pending timelocked action exists to accept or revoke.
    error NoPendingValue();

    /// @notice Pending value already exists and has not been revoked.
    error AlreadyPending();

    /* HELPERS */

    /// @dev Returns true if a pending value exists (validAt != 0).
    function isPending(uint64 validAt) internal pure returns (bool) {
        return validAt != 0;
    }

    /// @dev Reverts if the pending value is not yet executable.
    /// @dev Reverts with `NoPendingValue` if nothing is pending, or `TimelockNotExpired` if too early.
    function assertExecutable(uint64 validAt) internal view {
        if (validAt == 0) revert NoPendingValue();
        if (block.timestamp < validAt) revert TimelockNotExpired(validAt);
    }

    /// @dev Reverts if a pending value already exists.
    function assertNotPending(uint64 validAt) internal pure {
        if (validAt != 0) revert AlreadyPending();
    }

    /// @dev Reverts if no pending value exists.
    function assertIsPending(uint64 validAt) internal pure {
        if (validAt == 0) revert NoPendingValue();
    }

    /* UPDATE HELPERS */

    function update(PendingAddress storage self, address value, uint256 timelock) internal returns (uint64 validAt) {
        validAt = uint64(block.timestamp + timelock);
        self.value = value;
        self.validAt = validAt;
    }

    function update(PendingUint64 storage self, uint64 value, uint256 timelock) internal returns (uint64 validAt) {
        validAt = uint64(block.timestamp + timelock);
        self.value = value;
        self.validAt = validAt;
    }

    function update(PendingUint128 storage self, uint128 value, uint256 timelock) internal returns (uint64 validAt) {
        validAt = uint64(block.timestamp + timelock);
        self.value = value;
        self.validAt = validAt;
    }

    function update(PendingMarketHook storage self, address hook, uint256 permissions, uint256 timelock)
        internal
        returns (uint64 validAt)
    {
        validAt = uint64(block.timestamp + timelock);
        self.hook = hook;
        self.permissions = permissions;
        self.validAt = validAt;
    }

    function update(PendingUpgrade storage self, address newImplementation, bytes32 dataHash, uint256 timelock)
        internal
        returns (uint64 validAt)
    {
        validAt = uint64(block.timestamp + timelock);
        self.newImplementation = newImplementation;
        self.dataHash = dataHash;
        self.validAt = validAt;
    }

    /* CLEAR HELPERS */

    function clear(PendingAddress storage self) internal {
        self.value = address(0);
        self.validAt = 0;
    }

    function clear(PendingUint64 storage self) internal {
        self.value = 0;
        self.validAt = 0;
    }

    function clear(PendingUint128 storage self) internal {
        self.value = 0;
        self.validAt = 0;
    }

    function clear(PendingMarketHook storage self) internal {
        self.hook = address(0);
        self.permissions = 0;
        self.validAt = 0;
    }

    function clear(PendingUpgrade storage self) internal {
        self.newImplementation = address(0);
        self.dataHash = bytes32(0);
        self.validAt = 0;
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "solady/=lib/solady/",
    "bundler3/=lib/bundler3/",
    "ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/bundler3/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "morpho-blue/=lib/bundler3/lib/morpho-blue/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "prb-math/=lib/prb-math/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.