MEarnerManager

Description:

Proxy contract enabling upgradeable smart contract patterns. Delegates calls to an implementation contract.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "src/projects/earnerManager/MEarnerManager.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.26;

import { IERC20 } from "../../../lib/common/src/interfaces/IERC20.sol";

import {
    AccessControlUpgradeable
} from "../../../lib/common/lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol";

import { IndexingMath } from "../../libs/IndexingMath.sol";
import { UIntMath } from "../../../lib/common/src/libs/UIntMath.sol";

import { IMExtension } from "../../interfaces/IMExtension.sol";
import { IMTokenLike } from "../../interfaces/IMTokenLike.sol";
import { IMEarnerManager } from "./IMEarnerManager.sol";

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

abstract contract MEarnerManagerStorageLayout {
    /**
     * @dev   Struct to represent an account's balance, whitelisted status, and earning details like `feeRate` and earning principal.
     * @param balance       The current balance of the account.
     * @param isWhitelisted Whether the account is whitelisted by an earner manager.
     * @param feeRate       The fee rate that defines yield split between account and earner manager.
     * @param principal     The earning principal for the account.
     */
    struct Account {
        // Slot 1
        uint256 balance;
        // Slot 2
        bool isWhitelisted;
        uint16 feeRate;
        uint112 principal;
    }

    /// @custom:storage-location erc7201:M0.storage.MEarnerManager
    struct MEarnerManagerStorageStruct {
        // Slot 1
        address feeRecipient;
        // Slot 2
        uint256 totalSupply;
        // Slot 3
        uint112 totalPrincipal;
        bool wasEarningEnabled;
        uint128 disableIndex;
        // Slot 4
        mapping(address account => Account) accounts;
    }

    // keccak256(abi.encode(uint256(keccak256("M0.storage.MEarnerManager")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant _M_EARNER_MANAGER_STORAGE_LOCATION =
        0x1c4485857d96206482b943eeab7f941848f1c52b84a4bd59d8c2a3e8468f8300;

    function _getMEarnerManagerStorageLocation() internal pure returns (MEarnerManagerStorageStruct storage $) {
        assembly {
            $.slot := _M_EARNER_MANAGER_STORAGE_LOCATION
        }
    }
}

/**
 * @title M Extension where Earner Manager whitelists accounts and sets fee rates for them.
 * @author M0 Labs
 */
contract MEarnerManager is IMEarnerManager, AccessControlUpgradeable, MEarnerManagerStorageLayout, MExtension {
    /* ============ Variables ============ */

    /// @inheritdoc IMEarnerManager
    uint16 public constant ONE_HUNDRED_PERCENT = 10_000;

    /// @inheritdoc IMEarnerManager
    bytes32 public constant EARNER_MANAGER_ROLE = keccak256("EARNER_MANAGER_ROLE");

    /* ============ Constructor ============ */

    /**
     * @custom:oz-upgrades-unsafe-allow constructor
     * @notice Constructs MYieldFee Implementation contract
     * @dev    Sets immutable storage.
     * @param  mToken       The address of $M token.
     * @param  swapFacility The address of Swap Facility.
     */
    constructor(address mToken, address swapFacility) MExtension(mToken, swapFacility) {}

    /* ============ Initializer ============ */

    /**
     * @dev   Initializes the M extension token with earner manager role and different fee tiers.
     * @param name               The name of the token (e.g. "M Earner Manager").
     * @param symbol             The symbol of the token (e.g. "MEM").
     * @param admin              The address administrating the M extension. Can grant and revoke roles.
     * @param earnerManager      The address of earner manager
     * @param feeRecipient_      The address that will receive the fees from all the earners.
     */
    function initialize(
        string memory name,
        string memory symbol,
        address admin,
        address earnerManager,
        address feeRecipient_
    ) public virtual initializer {
        if (admin == address(0)) revert ZeroAdmin();
        if (earnerManager == address(0)) revert ZeroEarnerManager();

        __MExtension_init(name, symbol);

        _setFeeRecipient(feeRecipient_);

        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        _grantRole(EARNER_MANAGER_ROLE, earnerManager);
    }

    /* ============ Interactive Functions ============ */

    /// @inheritdoc IMEarnerManager
    function setAccountInfo(address account, bool status, uint16 feeRate) public onlyRole(EARNER_MANAGER_ROLE) {
        _setAccountInfo(account, status, feeRate);
    }

    /// @inheritdoc IMEarnerManager
    function setAccountInfo(
        address[] calldata accounts,
        bool[] calldata statuses,
        uint16[] calldata feeRates
    ) external onlyRole(EARNER_MANAGER_ROLE) {
        if (accounts.length == 0) revert ArrayLengthZero();
        if (accounts.length != statuses.length || accounts.length != feeRates.length) revert ArrayLengthMismatch();

        for (uint256 index_; index_ < accounts.length; ++index_) {
            _setAccountInfo(accounts[index_], statuses[index_], feeRates[index_]);
        }
    }

    /// @inheritdoc IMEarnerManager
    function setFeeRecipient(address feeRecipient_) external onlyRole(EARNER_MANAGER_ROLE) {
        _setFeeRecipient(feeRecipient_);
    }

    /// @inheritdoc IMEarnerManager
    function claimFor(address account) public returns (uint256 yieldWithFee, uint256 fee, uint256 yieldNetOfFee) {
        if (account == address(0)) revert ZeroAccount();

        (yieldWithFee, fee, yieldNetOfFee) = accruedYieldAndFeeOf(account);

        if (yieldWithFee == 0) return (0, 0, 0);

        // Emit the appropriate `YieldClaimed` and `Transfer` events.
        emit YieldClaimed(account, yieldNetOfFee);
        emit Transfer(address(0), account, yieldWithFee);

        MEarnerManagerStorageStruct storage $ = _getMEarnerManagerStorageLocation();

        // NOTE: No change in principal, only the balance is updated to include the newly claimed yield.
        unchecked {
            $.accounts[account].balance += yieldWithFee;
            $.totalSupply += yieldWithFee;
        }

        if (fee == 0) return (yieldWithFee, 0, yieldNetOfFee);

        address feeRecipient_ = $.feeRecipient;

        // Emit the appropriate `FeeClaimed` and `Transfer` events.
        emit FeeClaimed(account, feeRecipient_, fee);
        emit Transfer(account, feeRecipient_, fee);

        // Transfer fee to the fee recipient.
        _update(account, feeRecipient_, fee);
    }

    /// @inheritdoc IMEarnerManager
    function claimFor(
        address[] calldata accounts
    ) external returns (uint256[] memory yieldWithFees, uint256[] memory fees, uint256[] memory yieldNetOfFees) {
        if (accounts.length == 0) revert ArrayLengthZero();

        // Initialize the return arrays with the same length as the `accounts` array.
        yieldWithFees = new uint256[](accounts.length);
        fees = new uint256[](accounts.length);
        yieldNetOfFees = new uint256[](accounts.length);

        // NOTE: Expected to loop over unique whitelisted addresses; otherwise, no yield will be claimed.
        for (uint256 index_ = 0; index_ < accounts.length; ++index_) {
            (yieldWithFees[index_], fees[index_], yieldNetOfFees[index_]) = claimFor(accounts[index_]);
        }
    }

    /// @inheritdoc IMExtension
    function enableEarning() external override {
        MEarnerManagerStorageStruct storage $ = _getMEarnerManagerStorageLocation();

        if ($.wasEarningEnabled) revert EarningCannotBeReenabled();

        $.wasEarningEnabled = true;

        emit EarningEnabled(currentIndex());

        IMTokenLike(mToken).startEarning();
    }

    /// @inheritdoc IMExtension
    function disableEarning() external override {
        MEarnerManagerStorageStruct storage $ = _getMEarnerManagerStorageLocation();

        if (!isEarningEnabled()) revert EarningIsDisabled();

        emit EarningDisabled($.disableIndex = currentIndex());

        IMTokenLike(mToken).stopEarning(address(this));
    }

    /* ============ External/Public view functions ============ */

    /// @inheritdoc IMExtension
    function isEarningEnabled() public view override returns (bool) {
        MEarnerManagerStorageStruct storage $ = _getMEarnerManagerStorageLocation();

        return $.wasEarningEnabled && $.disableIndex == 0;
    }

    /// @inheritdoc IMEarnerManager
    function accruedYieldAndFeeOf(
        address account
    ) public view returns (uint256 yieldWithFee, uint256 fee, uint256 yieldNetOfFee) {
        Account storage accountInfo_ = _getMEarnerManagerStorageLocation().accounts[account];

        yieldWithFee = _getAccruedYield(accountInfo_.balance, accountInfo_.principal, currentIndex());
        uint16 feeRate_ = accountInfo_.feeRate;

        if (feeRate_ == 0 || yieldWithFee == 0) return (yieldWithFee, 0, yieldWithFee);

        unchecked {
            fee = (yieldWithFee * feeRate_) / ONE_HUNDRED_PERCENT;
            yieldNetOfFee = yieldWithFee - fee;
        }
    }

    /// @inheritdoc IMEarnerManager
    function accruedYieldOf(address account) public view returns (uint256 yieldNetOfFee) {
        (, , yieldNetOfFee) = accruedYieldAndFeeOf(account);
    }

    /// @inheritdoc IMEarnerManager
    function accruedFeeOf(address account) public view returns (uint256 fee) {
        (, fee, ) = accruedYieldAndFeeOf(account);
    }

    /// @inheritdoc IMEarnerManager
    function balanceWithYieldOf(address account) external view returns (uint256) {
        unchecked {
            return balanceOf(account) + accruedYieldOf(account);
        }
    }

    /// @inheritdoc IERC20
    function balanceOf(address account) public view override returns (uint256) {
        return _getMEarnerManagerStorageLocation().accounts[account].balance;
    }

    /// @inheritdoc IERC20
    function totalSupply() public view returns (uint256) {
        return _getMEarnerManagerStorageLocation().totalSupply;
    }

    /// @inheritdoc IMEarnerManager
    function projectedTotalSupply() public view returns (uint256) {
        return IndexingMath.getPresentAmountRoundedUp(totalPrincipal(), currentIndex());
    }

    /// @inheritdoc IMEarnerManager
    function totalPrincipal() public view returns (uint112) {
        return _getMEarnerManagerStorageLocation().totalPrincipal;
    }

    /// @inheritdoc IMEarnerManager
    function feeRecipient() public view returns (address) {
        return _getMEarnerManagerStorageLocation().feeRecipient;
    }

    /// @inheritdoc IMEarnerManager
    function isWhitelisted(address account) public view returns (bool) {
        return _getMEarnerManagerStorageLocation().accounts[account].isWhitelisted;
    }

    /// @inheritdoc IMEarnerManager
    function principalOf(address account) public view returns (uint112) {
        return _getMEarnerManagerStorageLocation().accounts[account].principal;
    }

    /// @inheritdoc IMEarnerManager
    function feeRateOf(address account) public view returns (uint16) {
        return _getMEarnerManagerStorageLocation().accounts[account].feeRate;
    }

    /// @inheritdoc IMExtension
    function currentIndex() public view override returns (uint128) {
        uint128 disableIndex_ = disableIndex();
        return disableIndex_ == 0 ? IMTokenLike(mToken).currentIndex() : disableIndex_;
    }

    /// @inheritdoc IMEarnerManager
    function disableIndex() public view returns (uint128) {
        return _getMEarnerManagerStorageLocation().disableIndex;
    }

    /// @inheritdoc IMEarnerManager
    function wasEarningEnabled() public view returns (bool) {
        return _getMEarnerManagerStorageLocation().wasEarningEnabled;
    }

    /* ============ Hooks For Internal Interactive Functions ============ */

    /**
     * @dev   Hook called before approving an allowance.
     * @param account  The account that is approving the allowance.
     * @param spender  The account that is being approved to spend tokens.
     */
    function _beforeApprove(address account, address spender, uint256 /* amount */) internal view override {
        MEarnerManagerStorageStruct storage $ = _getMEarnerManagerStorageLocation();

        _revertIfNotWhitelisted($, account);
        _revertIfNotWhitelisted($, spender);
    }

    /**
     * @dev    Hooks called before wrapping M into M Extension token.
     * @param  account   The account from which M is deposited.
     * @param  recipient The account receiving the minted M Extension token.
     */
    function _beforeWrap(address account, address recipient, uint256 /* amount */) internal view override {
        if (!isEarningEnabled()) revert EarningIsDisabled();

        MEarnerManagerStorageStruct storage $ = _getMEarnerManagerStorageLocation();

        _revertIfNotWhitelisted($, account);
        _revertIfNotWhitelisted($, recipient);
    }

    /**
     * @dev   Hook called before unwrapping M Extension token.
     * @param account The account from which M Extension token is burned.
     */
    function _beforeUnwrap(address account, uint256 /* amount */) internal view override {
        _revertIfNotWhitelisted(_getMEarnerManagerStorageLocation(), account);
    }

    /**
     * @dev   Hook called before transferring tokens.
     * @param sender    The sender's address.
     * @param recipient The recipient's address.
     */
    function _beforeTransfer(address sender, address recipient, uint256 /* amount */) internal view override {
        MEarnerManagerStorageStruct storage $ = _getMEarnerManagerStorageLocation();

        _revertIfNotWhitelisted($, msg.sender);

        _revertIfNotWhitelisted($, sender);
        _revertIfNotWhitelisted($, recipient);
    }

    /* ============ Internal Interactive Functions ============ */

    /**
     * @notice Sets the account info like:
     *         - whitelisting or removing account from whitelist,
     *         - fee rate for the account.
     * @param  account The address of the accounts to whitelist for earning or remove from the whitelist.
     * @param  status Whether an account is a whitelisted account, respectively, according to the admin.
     * @param  feeRate The fee rate, in bps, that will be taken from the yield generated by the account.
     */
    function _setAccountInfo(address account, bool status, uint16 feeRate) internal {
        if (account == address(0)) revert ZeroAccount();
        if (feeRate > ONE_HUNDRED_PERCENT) revert InvalidFeeRate();
        if (status == false && feeRate != 0) revert InvalidAccountInfo();

        Account storage accountInfo_ = _getMEarnerManagerStorageLocation().accounts[account];
        bool isWhitelisted_ = accountInfo_.isWhitelisted;

        // No change, no-op action
        if (!isWhitelisted_ && !status) return;

        // No change, no-op action
        if (isWhitelisted_ && status && accountInfo_.feeRate == feeRate) return;

        emit AccountInfoSet(account, status, feeRate);

        // Claim yield for an `account` as the action below will lead to the change in the account info.
        // NOTE: Handle addresses being re-whitelisted by claiming any previously accrued yield to the `feeRecipient`.
        claimFor(account);

        // Set up a new whitelisted account.
        if (!isWhitelisted_ && status) {
            accountInfo_.isWhitelisted = true;
            accountInfo_.feeRate = feeRate;
            return;
        }

        if (!status) {
            // Remove whitelisted account info.
            accountInfo_.isWhitelisted = false;
            // fee recipient will receive all yield from such 'un-whitelisted' accounts.
            accountInfo_.feeRate = ONE_HUNDRED_PERCENT;
        } else {
            // Change fee rate for the whitelisted account.
            accountInfo_.feeRate = feeRate;
        }
    }

    /**
     * @notice Sets the yield fee recipient that will receive part of the yield generated by token.
     * @dev    Reverts if the yield fee recipient is address zero.
     * @dev    Returns early if the yield fee recipient is the same as the current one.
     * @param  feeRecipient_ The yield fee recipient address.
     */
    function _setFeeRecipient(address feeRecipient_) internal {
        if (feeRecipient_ == address(0)) revert ZeroFeeRecipient();

        MEarnerManagerStorageStruct storage $ = _getMEarnerManagerStorageLocation();

        if ($.feeRecipient == feeRecipient_) return;

        // Yield fee recipient does not pay fees.
        _setAccountInfo(feeRecipient_, true, 0);

        $.feeRecipient = feeRecipient_;

        emit FeeRecipientSet(feeRecipient_);
    }

    /**
     * @dev   Mints `amount` tokens to `account`.
     * @param account The address that will receive tokens.
     * @param amount  The amount of tokens to mint.
     */
    function _mint(address account, uint256 amount) internal override {
        MEarnerManagerStorageStruct storage $ = _getMEarnerManagerStorageLocation();
        Account storage accountInfo_ = $.accounts[account];

        // Slightly underestimate the principal amount to be minted, round down in favor of protocol.
        uint112 principal_ = IndexingMath.getPrincipalAmountRoundedDown(amount, currentIndex());

        // NOTE: Can be `unchecked` because the max amount of $M is never greater than `type(uint240).max`.
        //       Can be `unchecked` because UIntMath.safe112 is used for principal addition safety for `principal[account]`
        unchecked {
            accountInfo_.balance += amount;
            $.totalSupply += amount;

            $.totalPrincipal = UIntMath.safe112(uint256($.totalPrincipal) + principal_);
            // No need for `UIntMath.safe112`, `accountInfo_.principal` cannot be greater than `totalPrincipal`.
            accountInfo_.principal += principal_;
        }

        emit Transfer(address(0), account, amount);
    }

    /**
     * @dev   Burns `amount` tokens from `account`.
     * @param account The address whose account balance will be decremented.
     * @param amount  The present amount of tokens to burn.
     */
    function _burn(address account, uint256 amount) internal override {
        MEarnerManagerStorageStruct storage $ = _getMEarnerManagerStorageLocation();
        Account storage accountInfo_ = $.accounts[account];

        // Slightly overestimate the principal amount to be burned and use safe value to avoid underflow in the unchecked block.
        uint112 fromPrincipal_ = accountInfo_.principal;
        uint112 principal_ = IndexingMath.getSafePrincipalAmountRoundedUp(amount, currentIndex(), fromPrincipal_);

        // NOTE: Can be `unchecked` because `_revertIfInsufficientBalance` is used.
        //       Can be `unchecked` because safety adjustment to `principal_` is applied above
        unchecked {
            accountInfo_.balance -= amount;
            $.totalSupply -= amount;

            accountInfo_.principal = fromPrincipal_ - principal_;
            $.totalPrincipal -= principal_;
        }

        emit Transfer(account, address(0), amount);
    }

    /**
     * @dev   Internal balance update function called on transfer.
     * @param sender    The sender's address.
     * @param recipient The recipient's address.
     * @param amount    The amount to be transferred.
     */
    function _update(address sender, address recipient, uint256 amount) internal override {
        MEarnerManagerStorageStruct storage $ = _getMEarnerManagerStorageLocation();
        Account storage senderAccount_ = $.accounts[sender];
        Account storage recipientAccount_ = $.accounts[recipient];

        // Slightly overestimate the principal amount to be moved on transfer
        uint112 fromPrincipal_ = senderAccount_.principal;
        uint112 principal_ = IndexingMath.getSafePrincipalAmountRoundedUp(amount, currentIndex(), fromPrincipal_);

        // NOTE: Can be `unchecked` because `_revertIfInsufficientBalance` is used in MExtension.
        //       Can be `unchecked` because safety adjustment to `principal_` is applied above, and
        unchecked {
            senderAccount_.balance -= amount;
            recipientAccount_.balance += amount;

            senderAccount_.principal = fromPrincipal_ - principal_;
            recipientAccount_.principal += principal_;
        }
    }

    /* ============ Internal View/Pure Functions ============ */

    /**
     * @dev    Compute the yield given a balance, principal and index.
     * @param  balance   The current balance of the account.
     * @param  principal The principal of the account.
     * @param  index     The current index.
     * @return The yield accrued since the last claim.
     */
    function _getAccruedYield(uint256 balance, uint112 principal, uint128 index) internal pure returns (uint256) {
        if (principal == 0) return 0;

        uint256 balanceWithYield_ = IndexingMath.getPresentAmountRoundedDown(principal, index);
        unchecked {
            return balanceWithYield_ > balance ? balanceWithYield_ - balance : 0;
        }
    }

    /**
     * @dev Reverts if `account` is not whitelisted by earner manager.
     */
    function _revertIfNotWhitelisted(MEarnerManagerStorageStruct storage $, address account) internal view {
        if (!$.accounts[account].isWhitelisted) revert NotWhitelisted(account);
    }
}
"
    },
    "lib/common/src/interfaces/IERC20.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.20 <0.9.0;

/**
 * @title  ERC20 Token Standard.
 * @author M^0 Labs
 * @dev    The interface as defined by EIP-20: https://eips.ethereum.org/EIPS/eip-20
 */
interface IERC20 {
    /* ============ Events ============ */

    /**
     * @notice Emitted when `spender` has been approved for `amount` of the token balance of `account`.
     * @param  account The address of the account.
     * @param  spender The address of the spender being approved for the allowance.
     * @param  amount  The amount of the allowance being approved.
     */
    event Approval(address indexed account, address indexed spender, uint256 amount);

    /**
     * @notice Emitted when `amount` tokens is transferred from `sender` to `recipient`.
     * @param  sender    The address of the sender who's token balance is decremented.
     * @param  recipient The address of the recipient who's token balance is incremented.
     * @param  amount    The amount of tokens being transferred.
     */
    event Transfer(address indexed sender, address indexed recipient, uint256 amount);

    /* ============ Interactive Functions ============ */

    /**
     * @notice Allows a calling account to approve `spender` to spend up to `amount` of its token balance.
     * @dev    MUST emit an `Approval` event.
     * @param  spender The address of the account being allowed to spend up to the allowed amount.
     * @param  amount  The amount of the allowance being approved.
     * @return Whether or not the approval was successful.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @notice Allows a calling account to transfer `amount` tokens to `recipient`.
     * @param  recipient The address of the recipient who's token balance will be incremented.
     * @param  amount    The amount of tokens being transferred.
     * @return Whether or not the transfer was successful.
     */
    function transfer(address recipient, uint256 amount) external returns (bool);

    /**
     * @notice Allows a calling account to transfer `amount` tokens from `sender`, with allowance, to a `recipient`.
     * @param  sender    The address of the sender who's token balance will be decremented.
     * @param  recipient The address of the recipient who's token balance will be incremented.
     * @param  amount    The amount of tokens being transferred.
     * @return Whether or not the transfer was successful.
     */
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /* ============ View/Pure Functions ============ */

    /**
     * @notice Returns the allowance `spender` is allowed to spend on behalf of `account`.
     * @param  account The address of the account who's token balance `spender` is allowed to spend.
     * @param  spender The address of an account allowed to spend on behalf of `account`.
     * @return The amount `spender` can spend on behalf of `account`.
     */
    function allowance(address account, address spender) external view returns (uint256);

    /**
     * @notice Returns the token balance of `account`.
     * @param  account The address of some account.
     * @return The token balance of `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /// @notice Returns the number of decimals UIs should assume all amounts have.
    function decimals() external view returns (uint8);

    /// @notice Returns the name of the contract/token.
    function name() external view returns (string memory);

    /// @notice Returns the symbol of the token.
    function symbol() external view returns (string memory);

    /// @notice Returns the current total supply of the token.
    function totalSupply() external view returns (uint256);
}
"
    },
    "lib/common/lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;


    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
    struct AccessControlStorage {
        mapping(bytes32 role => RoleData) _roles;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;

    function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
        assembly {
            $.slot := AccessControlStorageLocation
        }
    }

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    function __AccessControl_init() internal onlyInitializing {
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        return $._roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        return $._roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        AccessControlStorage storage $ = _getAccessControlStorage();
        bytes32 previousAdminRole = getRoleAdmin(role);
        $._roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (!hasRole(role, account)) {
            $._roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (hasRole(role, account)) {
            $._roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}
"
    },
    "src/libs/IndexingMath.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1

pragma solidity >=0.8.20 <0.9.0;

import { UIntMath } from "../../lib/common/src/libs/UIntMath.sol";

/**
 * @title  Helper library for indexing math functions.
 * @author M0 Labs
 */
library IndexingMath {
    /* ============ Variables ============ */

    /// @notice The scaling of indexes for exponent math.
    uint56 internal constant EXP_SCALED_ONE = 1e12;

    /* ============ Custom Errors ============ */

    /// @notice Emitted when a division by zero occurs.
    error DivisionByZero();

    /* ============ Exposed Functions ============ */

    /**
     * @dev    Returns the present amount (rounded down) given the principal amount and an index.
     * @param  principal The principal amount.
     * @param  index     An index.
     * @return The present amount rounded down.
     */
    function getPresentAmountRoundedDown(uint112 principal, uint128 index) internal pure returns (uint256) {
        unchecked {
            return (uint256(principal) * index) / EXP_SCALED_ONE;
        }
    }

    /**
     * @dev    Returns the present amount (rounded up) given the principal amount and an index.
     * @param  principal The principal amount.
     * @param  index     An index.
     * @return The present amount rounded up.
     */
    function getPresentAmountRoundedUp(uint112 principal, uint128 index) internal pure returns (uint256) {
        unchecked {
            return ((uint256(principal) * index) + (EXP_SCALED_ONE - 1)) / EXP_SCALED_ONE;
        }
    }

    /**
     * @dev    Returns the principal amount given the present amount, using the current index.
     * @param  presentAmount The present amount.
     * @param  index         An index.
     * @return The principal amount rounded down.
     */
    function getPrincipalAmountRoundedDown(uint256 presentAmount, uint128 index) internal pure returns (uint112) {
        if (index == 0) revert DivisionByZero();

        unchecked {
            // NOTE: While `uint256(presentAmount) * EXP_SCALED_ONE` can technically overflow, these divide/multiply functions are
            //       only used for the purpose of principal/present amount calculations for continuous indexing, and
            //       so for an `presentAmount` to be large enough to overflow this, it would have to be a possible result of
            //       `multiply112By128Down` or `multiply112By128Up`, which would already satisfy
            //       `uint256(presentAmount) * EXP_SCALED_ONE < type(uint240).max`.
            return UIntMath.safe112((presentAmount * EXP_SCALED_ONE) / index);
        }
    }

    /**
     * @dev    Returns the principal amount given the present amount, using the current index.
     * @param  presentAmount The present amount.
     * @param  index         An index.
     * @return The principal amount rounded up.
     */
    function getPrincipalAmountRoundedUp(uint256 presentAmount, uint128 index) internal pure returns (uint112) {
        if (index == 0) revert DivisionByZero();

        unchecked {
            // NOTE: While `uint256(presentAmount) * EXP_SCALED_ONE` can technically overflow, these divide/multiply functions are
            //       only used for the purpose of principal/present amount calculations for continuous indexing, and
            //       so for an `presentAmount` to be large enough to overflow this, it would have to be a possible result of
            //       `multiply112By128Down` or `multiply112By128Up`, which would already satisfy
            //       `uint256(presentAmount) * EXP_SCALED_ONE < type(uint240).max`.
            return UIntMath.safe112(((presentAmount * EXP_SCALED_ONE) + index - 1) / index);
        }
    }

    /**
     * @dev    Returns the safely capped principal amount given the present amount, using the current index.
     * @param  presentAmount The present amount.
     * @param  index         An index.
     * @param  maxPrincipalAmount The maximum principal amount.
     * @return The principal amount rounded up, capped at maxPrincipalAmount.
     */
    function getSafePrincipalAmountRoundedUp(
        uint256 presentAmount,
        uint128 index,
        uint112 maxPrincipalAmount
    ) internal pure returns (uint112) {
        uint112 principalAmount = getPrincipalAmountRoundedUp(presentAmount, index);
        return principalAmount > maxPrincipalAmount ? maxPrincipalAmount : principalAmount;
    }
}
"
    },
    "lib/common/src/libs/UIntMath.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.20 <0.9.0;

/**
 * @title  Library to perform safe math operations on uint types
 * @author M^0 Labs
 */
library UIntMath {
    /* ============ Custom Errors ============ */

    /// @notice Emitted when a passed value is greater than the maximum value of uint16.
    error InvalidUInt16();

    /// @notice Emitted when a passed value is greater than the maximum value of uint32.
    error InvalidUInt32();

    /// @notice Emitted when a passed value is greater than the maximum value of uint40.
    error InvalidUInt40();

    /// @notice Emitted when a passed value is greater than the maximum value of uint48.
    error InvalidUInt48();

    /// @notice Emitted when a passed value is greater than the maximum value of uint112.
    error InvalidUInt112();

    /// @notice Emitted when a passed value is greater than the maximum value of uint128.
    error InvalidUInt128();

    /// @notice Emitted when a passed value is greater than the maximum value of uint240.
    error InvalidUInt240();

    /* ============ Internal View/Pure Functions ============ */

    /**
     * @notice Casts a uint256 value to a uint16, ensuring that it is less than or equal to the maximum uint16 value.
     * @param  n The value to cast.
     * @return The value casted to uint16.
     */
    function safe16(uint256 n) internal pure returns (uint16) {
        if (n > type(uint16).max) revert InvalidUInt16();
        return uint16(n);
    }

    /**
     * @notice Casts a uint256 value to a uint32, ensuring that it is less than or equal to the maximum uint32 value.
     * @param  n The value to cast.
     * @return The value casted to uint32.
     */
    function safe32(uint256 n) internal pure returns (uint32) {
        if (n > type(uint32).max) revert InvalidUInt32();
        return uint32(n);
    }

    /**
     * @notice Casts a uint256 value to a uint40, ensuring that it is less than or equal to the maximum uint40 value.
     * @param  n The value to cast.
     * @return The value casted to uint40.
     */
    function safe40(uint256 n) internal pure returns (uint40) {
        if (n > type(uint40).max) revert InvalidUInt40();
        return uint40(n);
    }

    /**
     * @notice Casts a uint256 value to a uint48, ensuring that it is less than or equal to the maximum uint48 value.
     * @param  n The value to cast.
     * @return The value casted to uint48.
     */
    function safe48(uint256 n) internal pure returns (uint48) {
        if (n > type(uint48).max) revert InvalidUInt48();
        return uint48(n);
    }

    /**
     * @notice Casts a uint256 value to a uint112, ensuring that it is less than or equal to the maximum uint112 value.
     * @param  n The value to cast.
     * @return The value casted to uint112.
     */
    function safe112(uint256 n) internal pure returns (uint112) {
        if (n > type(uint112).max) revert InvalidUInt112();
        return uint112(n);
    }

    /**
     * @notice Casts a uint256 value to a uint128, ensuring that it is less than or equal to the maximum uint128 value.
     * @param  n The value to cast.
     * @return The value casted to uint128.
     */
    function safe128(uint256 n) internal pure returns (uint128) {
        if (n > type(uint128).max) revert InvalidUInt128();
        return uint128(n);
    }

    /**
     * @notice Casts a uint256 value to a uint240, ensuring that it is less than or equal to the maximum uint240 value.
     * @param  n The value to cast.
     * @return The value casted to uint240.
     */
    function safe240(uint256 n) internal pure returns (uint240) {
        if (n > type(uint240).max) revert InvalidUInt240();
        return uint240(n);
    }

    /**
     * @notice Limits a uint256 value to the maximum uint32 value.
     * @param  n The value to bound.
     * @return The value limited to within uint32 bounds.
     */
    function bound32(uint256 n) internal pure returns (uint32) {
        return uint32(min256(n, uint256(type(uint32).max)));
    }

    /**
     * @notice Limits a uint256 value to the maximum uint112 value.
     * @param  n The value to bound.
     * @return The value limited to within uint112 bounds.
     */
    function bound112(uint256 n) internal pure returns (uint112) {
        return uint112(min256(n, uint256(type(uint112).max)));
    }

    /**
     * @notice Limits a uint256 value to the maximum uint128 value.
     * @param  n The value to bound.
     * @return The value limited to within uint128 bounds.
     */
    function bound128(uint256 n) internal pure returns (uint128) {
        return uint128(min256(n, uint256(type(uint128).max)));
    }

    /**
     * @notice Limits a uint256 value to the maximum uint240 value.
     * @param  n The value to bound.
     * @return The value limited to within uint240 bounds.
     */
    function bound240(uint256 n) internal pure returns (uint240) {
        return uint240(min256(n, uint256(type(uint240).max)));
    }

    /**
     * @notice Compares two uint32 values and returns the larger one.
     * @param  a Value to compare.
     * @param  b Value to compare.
     * @return The larger value.
     */
    function max32(uint32 a, uint32 b) internal pure returns (uint32) {
        return a > b ? a : b;
    }

    /**
     * @notice Compares two uint40 values and returns the larger one.
     * @param  a Value to compare.
     * @param  b Value to compare.
     * @return The larger value.
     */
    function max40(uint40 a, uint40 b) internal pure returns (uint40) {
        return a > b ? a : b;
    }

    /**
     * @notice Compares two uint128 values and returns the larger one.
     * @param  a Value to compare.
     * @param  b Value to compare.
     * @return The larger value.
     */
    function max128(uint128 a, uint128 b) internal pure returns (uint128) {
        return a > b ? a : b;
    }

    /**
     * @notice Compares two uint240 values and returns the larger one.
     * @param  a Value to compare.
     * @param  b Value to compare.
     * @return The larger value.
     */
    function max240(uint240 a, uint240 b) internal pure returns (uint240) {
        return a > b ? a : b;
    }

    /**
     * @notice Compares two uint32 values and returns the lesser one.
     * @param  a Value to compare.
     * @param  b Value to compare.
     * @return The lesser value.
     */
    function min32(uint32 a, uint32 b) internal pure returns (uint32) {
        return a < b ? a : b;
    }

    /**
     * @notice Compares two uint40 values and returns the lesser one.
     * @param  a Value to compare.
     * @param  b Value to compare.
     * @return The lesser value.
     */
    function min40(uint40 a, uint40 b) internal pure returns (uint40) {
        return a < b ? a : b;
    }

    /**
     * @notice Compares two uint240 values and returns the lesser one.
     * @param  a Value to compare.
     * @param  b Value to compare.
     * @return The lesser value.
     */
    function min240(uint240 a, uint240 b) internal pure returns (uint240) {
        return a < b ? a : b;
    }

    /**
     * @notice Compares two uint112 values and returns the lesser one.
     * @param  a Value to compare.
     * @param  b Value to compare.
     * @return The lesser value.
     */
    function min112(uint112 a, uint112 b) internal pure returns (uint112) {
        return a < b ? a : b;
    }

    /**
     * @notice Compares two uint256 values and returns the lesser one.
     * @param  a Value to compare.
     * @param  b Value to compare.
     * @return The lesser value.
     */
    function min256(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }
}
"
    },
    "src/interfaces/IMExtension.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.26;

import { IERC20Extended } from "../../lib/common/src/interfaces/IERC20Extended.sol";

/**
 * @title  M Extension interface extending Extended ERC20,
 *         includes additional enable/disable earnings and index logic.
 * @author M0 Labs
 */
interface IMExtension is IERC20Extended {
    /* ============ Events ============ */

    /**
     * @notice Emitted when M extension earning is enabled.
     * @param  index The index at the moment earning is enabled.
     */
    event EarningEnabled(uint128 index);

    /**
     * @notice Emitted when M extension earning is disabled.
     * @param  index The index at the moment earning is disabled.
     */
    event EarningDisabled(uint128 index);

    /* ============ Custom Errors ============ */

    /// @notice Emitted when performing an operation that is not allowed when earning is disabled.
    error EarningIsDisabled();

    /// @notice Emitted when performing an operation that is not allowed when earning is enabled.
    error EarningIsEnabled();

    /**
     * @notice Emitted when there is insufficient balance to decrement from `account`.
     * @param  account The account with insufficient balance.
     * @param  balance The balance of the account.
     * @param  amount  The amount to decrement.
     */
    error InsufficientBalance(address account, uint256 balance, uint256 amount);

    /// @notice Emitted in constructor if M Token is 0x0.
    error ZeroMToken();

    /// @notice Emitted in constructor if Swap Facility is 0x0.
    error ZeroSwapFacility();

    /// @notice Emitted in `wrap` and `unwrap` functions if the caller is not the Swap Facility.
    error NotSwapFacility();

    /* ============ Interactive Functions ============ */

    /**
     * @notice Enables earning of extension token if allowed by the TTG Registrar and if it has never been done.
     * @dev SHOULD be virtual to allow extensions to override it.
     */
    function enableEarning() external;

    /**
     * @notice Disables earning of extension token if disallowed by the TTG Registrar and if it has never been done.
     * @dev SHOULD be virtual to allow extensions to override it.
     */
    function disableEarning() external;

    /**
     * @notice Wraps `amount` M from the caller into extension token for `recipient`.
     * @dev    Can only be called by the SwapFacility.
     * @param  recipient The account receiving the minted M extension token.
     * @param  amount    The amount of M extension token minted.
     */
    function wrap(address recipient, uint256 amount) external;

    /**
     * @notice Unwraps `amount` extension token from the caller into M for `recipient`.
     * @dev    Can only be called by the SwapFacility.
     * @param  recipient The account receiving the withdrawn M,
     *         it will always be the SwapFacility (keep `recipient` for backward compatibility).
     * @param  amount    The amount of M extension token burned.
     */
    function unwrap(address recipient, uint256 amount) external;

    /* ============ View/Pure Functions ============ */

    /// @notice The address of the M Token contract.
    function mToken() external view returns (address);

    /// @notice The address of the SwapFacility contract.
    function swapFacility() external view returns (address);

    /**
     * @notice Whether M extension earning is enabled.
     * @dev SHOULD be virtual to allow extensions to override it.
     */
    function isEarningEnabled() external view returns (bool);

    /**
     * @notice Returns the current index for M extension earnings.
     * @dev SHOULD be virtual to allow extensions to override it.
     */
    function currentIndex() external view returns (uint128);
}
"
    },
    "src/interfaces/IMTokenLike.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.26;

/**
 * @title  Subset of M Token interface required for source contracts.
 * @author M0 Labs
 */
interface IMTokenLike {
    /* ============ Custom Errors ============ */

    /// @notice Emitted when calling `stopEarning` for an account approved as earner by TTG.
    error IsApprovedEarner();

    /// @notice Emitted when calling `startEarning` for an account not approved as earner by TTG.
    error NotApprovedEarner();

    /* ============ Interactive Functions ============ */

    /**
     * @notice Allows a calling account to approve `spender` to spend up to `amount` of its token balance.
     * @dev    MUST emit an `Approval` event.
     * @param  spender The address of the account being allowed to spend up to the allowed amount.
     * @param  amount  The amount of the allowance being approved.
     * @return Whether or not the approval was successful.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @notice Approves `spender` to spend up to `amount` of the token balance of `owner`, via a signature.
     * @param  owner    The address of the account who's token balance is being approved to be spent by `spender`.
     * @param  spender  The address of an account allowed to spend on behalf of `owner`.
     * @param  value    The amount of the allowance being approved.
     * @param  deadline The last timestamp where the signature is still valid.
     * @param  v        An ECDSA secp256k1 signature parameter (EIP-2612 via EIP-712).
     * @param  r        An ECDSA secp256k1 signature parameter (EIP-2612 via EIP-712).
     * @param  s        An ECDSA secp256k1 signature parameter (EIP-2612 via EIP-712).
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @notice Approves `spender` to spend up to `amount` of the token balance of `owner`, via a signature.
     * @param  owner     The address of the account who's token balance is being approved to be spent by `spender`.
     * @param  spender   The address of an account allowed to spend on behalf of `owner`.
     * @param  value     The amount of the allowance being approved.
     * @param  deadline  The last timestamp where the signature is still valid.
     * @param  signature An arbitrary signature (EIP-712).
     */
    function permit(address owner, address spender, uint256 value, uint256 deadline, bytes memory signature) external;

    /**
     * @notice Allows a calling account to transfer `amount` tokens to `recipient`.
     * @param  recipient The address of the recipient who's token balance will be incremented.
     * @param  amount    The amount of tokens being transferred.
     * @return success   Whether or not the transfer was successful.
     */
    function transfer(address recipient, uint256 amount) external returns (bool);

    /**
     * @notice Allows a calling account to transfer `amount` tokens from `sender`, with allowance, to a `recipient`.
     * @param  sender    The address of the sender who's token balance will be decremented.
     * @param  recipient The address of the recipient who's token balance will be incremented.
     * @param  amount    The amount of tokens being transferred.
     * @return success   Whether or not the transfer was successful.
     */
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /// @notice Starts earning for caller if allowed by the Registrar.
    function startEarning() external;

    /**
     * @notice Stops earning for `account`.
     * @dev    MUST revert if `account` is an approved earner in TTG Registrar.
     * @param  account The account to stop earning for.
     */
    function stopEarning(address account) external;

    /* ============ View/Pure Functions ============ */

    /**
     * @notice Checks if account is an earner.
     * @param  account The account to check.
     * @return earning True if account is an earner, false otherwise.
     */
    function isEarning(address account) external view returns (bool);

    /**
     * @notice Returns the token balance of `account`.
     * @param  account The address of some account.
     * @return balance The token balance of `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @notice Returns the token balance of `account`.
     * @param  account The address of some account.
     * @return principal The principal token balance of `account`.
     */
    function principalBalanceOf(address account) external view returns (uint240);

    /// @notice The current index that would be written to storage if `updateIndex` is called.
    function currentIndex() external view returns (uint128);

    /// @notice The current value of earner rate in basis points.
    function earnerRate() external view returns (uint32);

    /// @notice Returns the EIP712 domain separator used in the encoding of a signed digest.
    function DOMAIN_SEPARATOR() external view returns (bytes32);

    /// @notice Returns the EIP712 typehash used in the encoding of the digest for the permit function.
    function PERMIT_TYPEHASH() external view returns (bytes32);

    /// @notice Updates the index and returns it.
    function updateIndex() external returns (uint128);
}
"
    },
    "src/projects/earnerManager/IMEarnerManager.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.26;

/**
 * @title M Extension where Earner Manager whitelists earners and sets fee rates for them.
 * @author M0 Labs
 */
interface IMEarnerManager {
    /* ============ Events ============ */

    /**
     * @notice Emitted when an account's yield is claimed.
     * @param  account   The address that yield is claimed for.
     * @param  yield     The amount of M extension yield claimed.
     */
    event YieldClaimed(address indexed account, uint256 yield);

    /**
     * @notice Emitted when an account's yield fee is claimed.
     * @param  account      The address that yield fee is claimed for.
     * @param  feeRecipient The address of the fee recipient.
     * @param  fee          The amount of M extension yield fee claimed.
     */
    event FeeClaimed(address indexed account, address indexed feeRecipient, uint256 fee);

    /**
     * @notice Emitted when account is added/removed to/from  the whitelist or fee rate is adjusted
     * @param  account   The address to set earner status and details.
     * @param  status    The whitelisted status of account.
     * @param  feeRate   The fee rate in bps of the account.
     */
    event AccountInfoSet(address indexed account, bool status, uint16 feeRate);

    /**
     * @notice Emitted when the fee recipient is set.
     * @param  feeRecipient The address of the new fee recipient.
     */
    event FeeRecipientSet(address indexed feeRecipient);

    /* ============ Custom Errors ============ */

    /// @notice Emitted in constructor if fee recipient is 0x0.
    error ZeroFeeRecipient();

    /// @notice Emitted in constructor if earner manager is 0x0.
    error ZeroEarnerManager();

    /// @notice Emitted in constructor if default admin is 0x0.
    error ZeroAdmin();

    /// @notice Emitted if account is 0x0.
    error ZeroAccount();

    /// @notice Emitted if the fee rate provided exceeds 100% in bps.
    error InvalidFeeRate();

    /// @notice Emitted if account is not whitelisted and fee rate is not zero.
    error InvalidAccountInfo();

    /// @notice Emitted if the account is not whitelisted.
    error NotWhitelisted(address account);

    /// @notice Emitted in `setAccountInfo` if lengths of arrays mismatch.
    error ArrayLengthMismatch();

    /// @notice Emitted in `setAccountInfo` if the array is empty.
    error ArrayLengthZero();

    /// @notice Emitted in `enableEarning` if earning was already previously enabled.
    error EarningCannotBeReenabled();

    /* ============ Interactive Functions ============ */

    /**
     * @notice Claims accrued yield to the account and % in fees to fee recipient.
     * @param  account The address of the account to claim yield for.
     * @return yieldWithFee The total amount of M extension yield claimed for the account.
     * @return fee The amount of M extension yield fee sent to fee recipient.
     * @return yieldNetOfFee The amount of M extension yield net of fees.
     */
    function claimFor(address account) external returns (uint256, uint256, uint256);

    /**
     * @notice Claims accrued yield to the accounts and % in fees to fee recipient.
     * @param  accounts The addresses of the accounts to claim yield for.
     * @return yieldWithFees The total amount of M extension yield claimed for each account.
     * @return fees The amount of M extension yield fee sent to fee recipient for each account.
     * @return yieldNetOfFees The amount of M extension yield net of fees for each account.
     */
    function claimFor(
        address[] calldata accounts
    ) external returns (uint256[] memory yieldWithFees, uint256[] memory fees, uint256[] memory yieldNetOfFees);

    /**
     * @notice Sets the account info like:
     *         - whitelisting or removing account from whitelist,
     *         - fee rate for the account.
     * @dev    MUST only be callable by the EARNER_MANAGER_ROLE.
     * @dev    SHOULD revert if account is 0x0.
     * @param  account The address of the account to whitelist for earning.
     * @param  status  Whether the account is whitelisted as an earner.
     * @param  feeRate The fee rate, in bps, that will be taken from the yield generated by the account.
     */
    function setAccountInfo(address account, bool status, uint16 feeRate) external;

    /**
     * @notice Sets the account info like:
     *         - whitelisting or removing account from whitelist,
     *         - fee rate for the account.
     * @dev    MUST only be callable by the EARNER_MANAGER_ROLE.
     * @dev    SHOULD revert if account is 0x0.
     * @param  accounts The addresses of the accounts to whitelist for earning or remove from the whitelist.
     * @param  statuses Whether each account is a whitelisted, respectively, according to the admin.
     * @param  feeRates The fee rate, in bps, that will be taken from the yield generated by the accounts.
     */
    function setAccountInfo(address[] calldata accounts, bool[] calldata statuses, uint16[] calldata feeRates) external;

    /**
     * @notice Sets the yield fee recipient.
     * @dev    MUST only be callable by the EARNER_MANAGER_ROLE.
     * @dev    SHOULD revert if `feeRecipient` is 0x0.
     * @dev    SHOULD return early if `feeRecipient` is already the fee recipient.
     * @param  feeRecipient The address of the new fee recipient.
     */
    function setFeeRecipient(address feeRecipient) external;

    /* ============ View/Pure Functions ============ */

    /// @notice Returns total accrued yield, fee and yield net of fee for `account`.
    function accruedYieldAndFeeOf(address account) external view returns (uint256, uint256, uint256);

    /// @notice Returns yield net of fee for `account`.
    function accruedYieldOf(address account) external view returns (uint256);

    /// @notice Returns fee accrued as a part of yield for `account`.
    function accruedFeeOf(address account) external view returns (uint256);

    /// @notice Returns balance with yield net of fee for `account`.
    function balanceWithYieldOf(address account) external view returns (uint256);

    /// @notice Returns the fee rate in basis points for `account` - [0..100%]
    function feeRateOf(address account) external view returns (uint16);

    /// @notice Returns the principal accruing yield for `account`.
    function principalOf(address account) external view returns (uint112);

    /// @notice Returns whether `account` is whitelisted for earning yield and be whitelisted holder of M extension token.
    function isWhitelisted(address account) external view returns (bool);

    /// @notice The address of the yield fee recipient for all whitelisted accounts.
    function feeRecipient() external view returns (address);

    /// @notice The M index when earning for the M extension was disabled.
    function disableIndex() external view returns (uint128);

    /// @notice Whether earning was enabled at least once for this M extension.
    function wasEarningEnabled() external view returns (bool);

    /// @notice The projected total supply if all accrued yield was claimed at this moment.
    function projectedTotalSupply() external view returns (uint256);

    /// @notice The total amount of principal of all whitelisted accounts.
    function totalPrincipal() external view returns (uint112);

    /// @notice 100% in basis points.
    function ONE_HUNDRED_PERCENT() external view returns (uint16);

    /// @notice The role that can manage the yield recipient.
    function EARNER_MANAGER_ROLE() external view returns (bytes32);
}
"
    },
    "src/MExtension.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.26;

import { ERC20ExtendedUpgradeable } from "../lib/common/src/ERC20ExtendedUpgradeable.sol";

import { IERC20 } from "../lib/common/src/interfaces/IERC20.sol";

import { IMTokenLike } from "./interfaces/IMTokenLike.sol";
import { IMExtension } from "./interfaces/IMExtension.sol";
import { ISwapFacility } from "./swap/interfaces/ISwapFacility.sol";

/**
 * @title  MExtension
 * @notice Upgradeable ERC20 Token contract for wrapping M into a non-rebasing token.
 * @author M0 Labs
 */
abstract contract MExtension is IMExtension, ERC20ExtendedUpgradeable {
    /* ============ Variables ============ */

    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    /// @inheritdoc IMExtension
    address public immutable mToken

Tags:
ERC20, ERC165, Proxy, Swap, Yield, Upgradeable, Factory|addr:0x4ffbc316cf29e8eb39cbf819cfd3d5f5b34033ef|verified:true|block:23598827|tx:0xacbd8462778c95427f44a48a907f9764353ad4d3b921b9980c22aa595e71c70c|first_check:1760725128

Submitted on: 2025-10-17 20:18:48

Comments

Log in to comment.

No comments yet.