Skip to content
Verified contractExactBUSL-1.1

LinearCreditDebtTracker

Address0x3bfe07e547e35f1debe8944eb3fa6d13f75205b8
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
23,324,054
Creation transaction
0xb5dc781fc8…8480b7a9ce

22 files

src/components/value/position-trackers/LinearCreditDebtTracker.sol

// SPDX-License-Identifier: BUSL-1.1

/*
    This file is part of the Onyx Protocol.

    (c) Enzyme Foundation <[email protected]>

    For the full license information, please view the LICENSE
    file that was distributed with this source code.
*/

pragma solidity 0.8.28;

import {IPositionTracker} from "src/components/value/position-trackers/IPositionTracker.sol";
import {ComponentHelpersMixin} from "src/components/utils/ComponentHelpersMixin.sol";
import {StorageHelpersLib} from "src/utils/StorageHelpersLib.sol";

/// @title LinearCreditDebtTracker Contract
/// @author Enzyme Foundation <[email protected]>
/// @notice An IPositionTracker implementation that tracks linear credit and/or debt positions
contract LinearCreditDebtTracker is IPositionTracker, ComponentHelpersMixin {
    //==================================================================================================================
    // Types
    //==================================================================================================================

    /// @dev Stores information about a credit or debt line-item
    /// @param totalValue The total value of the item (quoted in the Shares value asset), written down linearly over time
    /// @param settledValue The settled, non-linear value of the item (quoted in the Shares value asset)
    /// @param id The unique identifier of the item
    /// @param index The array index of the item in `ids[]`
    /// @param start The start timestamp of the linear write-down period
    /// @param duration The duration of the linear write-down period (in seconds)
    struct Item {
        // 1st slot
        int128 totalValue;
        int128 settledValue;
        // 2nd slot
        uint24 id;
        uint24 index;
        uint40 start;
        uint32 duration;
    }

    //==================================================================================================================
    // Storage
    //==================================================================================================================

    bytes32 private constant LINEAR_CREDIT_DEBT_TRACKER_STORAGE_LOCATION =
        0xf3c5e97ea0f49b3293469a3b3dca5503879e1f21da2c7f1e770e480cdbe07300;
    string private constant LINEAR_CREDIT_DEBT_TRACKER_STORAGE_LOCATION_ID = "LinearCreditDebtTracker";

    /// @custom:storage-location erc7201:enzyme.LinearCreditDebtTracker
    /// @param lastItemId The id of the last item that was added
    /// @param ids The list of active item ids (all items that have not been removed)
    /// @param idToItem A mapping of item ids to their corresponding Item info
    struct LinearCreditDebtTrackerStorage {
        uint24 lastItemId; // starts from 1
        uint24[] ids;
        mapping(uint24 => Item) idToItem;
    }

    function __getLinearCreditDebtTrackerStorage() private pure returns (LinearCreditDebtTrackerStorage storage $) {
        bytes32 location = LINEAR_CREDIT_DEBT_TRACKER_STORAGE_LOCATION;
        assembly {
            $.slot := location
        }
    }

    //==================================================================================================================
    // Events
    //==================================================================================================================

    event ItemAdded(uint24 id, int128 totalValue, uint40 start, uint32 duration, string description);

    event ItemRemoved(uint24 id);

    event ItemTotalSettledUpdated(uint24 id, int128 totalSettled);

    //==================================================================================================================
    // Errors
    //==================================================================================================================

    error LinearCreditDebtTracker__AddItem__EmptyTotalValue();

    error LinearCreditDebtTracker__RemoveItem__DoesNotExist();

    error LinearCreditDebtTracker__UpdateSettledValue__DoesNotExist();

    //==================================================================================================================
    // Constructor
    //==================================================================================================================

    constructor() {
        StorageHelpersLib.verifyErc7201LocationForId({
            _location: LINEAR_CREDIT_DEBT_TRACKER_STORAGE_LOCATION,
            _id: LINEAR_CREDIT_DEBT_TRACKER_STORAGE_LOCATION_ID
        });
    }

    //==================================================================================================================
    // Item management (access: Shares admin or owner)
    //==================================================================================================================

    /// @notice Adds a new line-item to the tracker
    /// @param _totalValue The total value of the item (quoted in the Shares value asset), written down linearly over time
    /// @param _start The start timestamp of the linear write-down period
    /// @param _duration The duration of the linear write-down period (in seconds)
    /// @param _description A description of the item
    /// @return id_ The id of the new line-item
    /// @dev A _duration of 0 indicates a discrete value change at the _start timestamp
    function addItem(int128 _totalValue, uint40 _start, uint32 _duration, string calldata _description)
        external
        onlyAdminOrOwner
        returns (uint24 id_)
    {
        require(_totalValue != 0, LinearCreditDebtTracker__AddItem__EmptyTotalValue());

        LinearCreditDebtTrackerStorage storage $ = __getLinearCreditDebtTrackerStorage();
        id_ = ++$.lastItemId; // first item will be `id_ = 1`
        uint24 index = uint24(getItemsCount());

        $.ids.push(id_);
        $.idToItem[id_] =
            Item({totalValue: _totalValue, settledValue: 0, id: id_, index: index, start: _start, duration: _duration});

        emit ItemAdded({id: id_, totalValue: _totalValue, start: _start, duration: _duration, description: _description});
    }

    /// @notice Removes an existing line-item from the tracker
    function removeItem(uint24 _id) external onlyAdminOrOwner {
        Item memory item = getItem({_id: _id});
        require(item.id != 0, LinearCreditDebtTracker__RemoveItem__DoesNotExist());

        LinearCreditDebtTrackerStorage storage $ = __getLinearCreditDebtTrackerStorage();
        uint256 finalIndex = getItemsCount() - 1;
        if (item.index != finalIndex) {
            Item memory finalItem = __getItemAtIndex({_index: finalIndex});
            // move final item to old item's index
            $.ids[item.index] = finalItem.id;
            $.idToItem[finalItem.id].index = item.index;
        }
        $.ids.pop();
        delete $.idToItem[_id];

        emit ItemRemoved({id: _id});
    }

    /// @notice Updates the settled value of an existing line-item, written down immediately
    /// @param _id The line-item id
    /// @param _totalSettled The total settled value of the line-item (quoted in the Shares value asset)
    function updateSettledValue(uint24 _id, int128 _totalSettled) external onlyAdminOrOwner {
        require(getItem({_id: _id}).id != 0, LinearCreditDebtTracker__UpdateSettledValue__DoesNotExist());

        LinearCreditDebtTrackerStorage storage $ = __getLinearCreditDebtTrackerStorage();
        $.idToItem[_id].settledValue = _totalSettled;

        emit ItemTotalSettledUpdated({id: _id, totalSettled: _totalSettled});
    }

    //==================================================================================================================
    // Position value
    //==================================================================================================================

    /// @notice Calculates the value of a line-item at the current timestamp
    /// @param _id The line-item id
    /// @return value_ The value of the line-item (quoted in the Shares value asset)
    /// @dev Cases:
    /// - prior to item.start = settled value only
    /// - while within "item.start + item.duration" = settled value + linearly pro-rated total value
    /// - otherwise = settled value + total value
    function calcItemValue(uint24 _id) public view returns (int256 value_) {
        Item memory item = getItem({_id: _id});

        // Handle cases outside of start and stop bounds
        if (block.timestamp <= item.start) {
            return item.settledValue;
        } else if (block.timestamp >= item.start + item.duration) {
            return item.settledValue + item.totalValue;
        }

        uint256 lapsed = block.timestamp - item.start;

        int256 proRatedValue = item.totalValue * int256(lapsed) / int256(uint256(item.duration));

        return item.settledValue + proRatedValue;
    }

    /// @inheritdoc IPositionTracker
    function getPositionValue() external view override returns (int256 value_) {
        uint24[] memory ids = getItemIds();
        for (uint256 i; i < ids.length; i++) {
            value_ += calcItemValue({_id: ids[i]});
        }

        return value_;
    }

    //==================================================================================================================
    // Misc
    //==================================================================================================================

    function __getItemAtIndex(uint256 _index) internal view returns (Item memory item_) {
        return getItem({_id: __getLinearCreditDebtTrackerStorage().ids[_index]});
    }

    //==================================================================================================================
    // State getters
    //==================================================================================================================

    function getItem(uint24 _id) public view returns (Item memory item_) {
        return __getLinearCreditDebtTrackerStorage().idToItem[_id];
    }

    function getItemIds() public view returns (uint24[] memory ids_) {
        return __getLinearCreditDebtTrackerStorage().ids;
    }

    function getItemsCount() public view returns (uint256 count_) {
        return __getLinearCreditDebtTrackerStorage().ids.length;
    }

    function getLastItemId() public view returns (uint24 id_) {
        return __getLinearCreditDebtTrackerStorage().lastItemId;
    }
}

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * 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.
     *
     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
     */
    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/token/ERC20/ERC20Upgradeable.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {
    /// @custom:storage-location erc7201:openzeppelin.storage.ERC20
    struct ERC20Storage {
        mapping(address account => uint256) _balances;

        mapping(address account => mapping(address spender => uint256)) _allowances;

        uint256 _totalSupply;

        string _name;
        string _symbol;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;

    function _getERC20Storage() private pure returns (ERC20Storage storage $) {
        assembly {
            $.slot := ERC20StorageLocation
        }
    }

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
        __ERC20_init_unchained(name_, symbol_);
    }

    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        ERC20Storage storage $ = _getERC20Storage();
        $._name = name_;
        $._symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        ERC20Storage storage $ = _getERC20Storage();
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            $._totalSupply += value;
        } else {
            uint256 fromBalance = $._balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                $._balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                $._totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                $._balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        ERC20Storage storage $ = _getERC20Storage();
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        $._allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance < type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

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-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol

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

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

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

pragma solidity ^0.8.20;

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

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

src/components/utils/ComponentHelpersMixin.sol

// SPDX-License-Identifier: BUSL-1.1

/*
    This file is part of the Onyx Protocol.

    (c) Enzyme Foundation <[email protected]>

    For the full license information, please view the LICENSE
    file that was distributed with this source code.
*/

pragma solidity 0.8.28;

import {IComponentProxy} from "src/interfaces/IComponentProxy.sol";
import {Shares} from "src/shares/Shares.sol";

/// @title ComponentHelpersMixin Contract
/// @author Enzyme Foundation <[email protected]>
/// @notice Mixin of helpers for IComponentProxy implementations
abstract contract ComponentHelpersMixin {
    error ComponentHelpersMixin__OnlyAdminOrOwner__Unauthorized();
    error ComponentHelpersMixin__OnlyShares__Unauthorized();

    modifier onlyAdminOrOwner() {
        require(__isAdminOrOwner(msg.sender), ComponentHelpersMixin__OnlyAdminOrOwner__Unauthorized());
        _;
    }

    modifier onlyShares() {
        require(msg.sender == __getShares(), ComponentHelpersMixin__OnlyShares__Unauthorized());
        _;
    }

    function __getShares() internal view returns (address) {
        return IComponentProxy(address(this)).SHARES();
    }

    function __isAdminOrOwner(address _who) internal view returns (bool) {
        return Shares(__getShares()).isAdminOrOwner(_who);
    }
}

src/components/value/position-trackers/IPositionTracker.sol

// SPDX-License-Identifier: BUSL-1.1

/*
    This file is part of the Onyx Protocol.

    (c) Enzyme Foundation <[email protected]>

    For the full license information, please view the LICENSE
    file that was distributed with this source code.
*/

pragma solidity ^0.8.0;

/// @title IPositionTracker Interface
/// @author Enzyme Foundation <[email protected]>
interface IPositionTracker {
    /// @notice Returns the current +/- value of the position quoted in the Shares value asset
    /// @return value_ The value (18-decimal precision)
    function getPositionValue() external view returns (int256 value_);
}

src/interfaces/IComponentProxy.sol

// SPDX-License-Identifier: BUSL-1.1

/*
    This file is part of the Onyx Protocol.

    (c) Enzyme Foundation <[email protected]>

    For the full license information, please view the LICENSE
    file that was distributed with this source code.
*/

pragma solidity ^0.8.0;

/// @title IComponentProxy Interface
/// @author Enzyme Foundation <[email protected]>
interface IComponentProxy {
    function SHARES() external view returns (address);
}

src/interfaces/IFeeHandler.sol

// SPDX-License-Identifier: BUSL-1.1

/*
    This file is part of the Onyx Protocol.

    (c) Enzyme Foundation <[email protected]>

    For the full license information, please view the LICENSE
    file that was distributed with this source code.
*/

pragma solidity ^0.8.0;

/// @title IFeeHandler Interface
/// @author Enzyme Foundation <[email protected]>
interface IFeeHandler {
    function getTotalValueOwed() external view returns (uint256 totalValueOwed_);

    function settleDynamicFeesGivenPositionsValue(uint256 _totalPositionsValue) external;

    function settleEntranceFeeGivenGrossShares(uint256 _grossSharesAmount) external returns (uint256 feeShares_);

    function settleExitFeeGivenGrossShares(uint256 _grossSharesAmount) external returns (uint256 feeShares_);
}

src/interfaces/ISharesTransferValidator.sol

// SPDX-License-Identifier: BUSL-1.1

/*
    This file is part of the Onyx Protocol.

    (c) Enzyme Foundation <[email protected]>

    For the full license information, please view the LICENSE
    file that was distributed with this source code.
*/

pragma solidity ^0.8.0;

/// @title ISharesTransferValidator Interface
/// @author Enzyme Foundation <[email protected]>
interface ISharesTransferValidator {
    function validateSharesTransfer(address _from, address _to, uint256 _amount) external;
}

src/interfaces/IValuationHandler.sol

// SPDX-License-Identifier: BUSL-1.1

/*
    This file is part of the Onyx Protocol.

    (c) Enzyme Foundation <[email protected]>

    For the full license information, please view the LICENSE
    file that was distributed with this source code.
*/

pragma solidity ^0.8.0;

/// @title IValuationHandler Interface
/// @author Enzyme Foundation <[email protected]>
interface IValuationHandler {
    function convertAssetAmountToValue(address _asset, uint256 _assetAmount) external view returns (uint256 value_);

    function convertValueToAssetAmount(uint256 _value, address _asset) external view returns (uint256 assetAmount_);

    function getDefaultSharePrice() external view returns (uint256);

    function getSharePrice() external view returns (uint256 price_, uint256 timestamp_);

    function getShareValue() external view returns (uint256 value_, uint256 timestamp_);
}

src/shares/Shares.sol

// SPDX-License-Identifier: BUSL-1.1

/*
    This file is part of the Onyx Protocol.

    (c) Enzyme Foundation <[email protected]>

    For the full license information, please view the LICENSE
    file that was distributed with this source code.
*/

pragma solidity 0.8.28;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol";
import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {IFeeHandler} from "src/interfaces/IFeeHandler.sol";
import {ISharesTransferValidator} from "src/interfaces/ISharesTransferValidator.sol";
import {IValuationHandler} from "src/interfaces/IValuationHandler.sol";
import {StorageHelpersLib} from "src/utils/StorageHelpersLib.sol";

/// @title Shares Contract
/// @author Enzyme Foundation <[email protected]>
/// @notice Shares token with registries and issuance-related logic
/// @dev The core-most contract.
/// Security notes:
/// - there are no built-in protections against:
///   - a very low totalSupply() (e.g., "inflation attack")
///   - a very low share value
contract Shares is ERC20Upgradeable, Ownable2StepUpgradeable {
    using SafeERC20 for IERC20;

    //==================================================================================================================
    // Storage
    //==================================================================================================================

    bytes32 private constant SHARES_STORAGE_LOCATION =
        0xbe724a55f726228f14b884d45d89388bc2a03793a0006937116ea1275a51fb00;
    string private constant SHARES_STORAGE_LOCATION_ID = "Shares";

    /// @custom:storage-location erc7201:enzyme.Shares
    /// @param valueAsset A representation of the asset of account in which core values are reported (e.g., USD)
    /// @param feeHandler The contract that handles fees (settlement, claims, accounting)
    /// @param sharesTransferValidator A contract that supplies shares transfer validation
    /// @param valuationHandler The contract that handles valuation-related operations
    /// @param isDepositHandler True if the account is an allowed deposit handler
    /// @param isRedeemHandler True if the account is an allowed redeem handler
    /// @param isAdmin True if the account is an admin
    /// @dev `valueAsset` is not used within the system, but is stored on-chain in case needed by integrators.
    struct SharesStorage {
        bytes32 valueAsset;
        address feeHandler;
        address sharesTransferValidator;
        address valuationHandler;
        mapping(address => bool) isDepositHandler;
        mapping(address => bool) isRedeemHandler;
        mapping(address => bool) isAdmin;
    }

    function __getSharesStorage() private pure returns (SharesStorage storage $) {
        bytes32 location = SHARES_STORAGE_LOCATION;
        assembly {
            $.slot := location
        }
    }

    //==================================================================================================================
    // Events
    //==================================================================================================================

    event AdminAdded(address admin);

    event AdminRemoved(address admin);

    event AssetWithdrawn(address caller, address asset, address to, uint256 amount);

    event DepositHandlerAdded(address depositHandler);

    event DepositHandlerRemoved(address depositHandler);

    event FeeHandlerSet(address feeHandler);

    event RedeemHandlerAdded(address redeemHandler);

    event RedeemHandlerRemoved(address redeemHandler);

    event SharesTransferValidatorSet(address validator);

    event ValuationHandlerSet(address valuationHandler);

    event ValueAssetSet(bytes32 valueAsset);

    //==================================================================================================================
    // Errors
    //==================================================================================================================

    error Shares__AddAdmin__AlreadyAdded();

    error Shares__AddAllowedHolder__AlreadyAdded();

    error Shares__AddDepositHandler__AlreadyAdded();

    error Shares__AddRedeemHandler__AlreadyAdded();

    error Shares__AuthTransfer__Unauthorized();

    error Shares__GetDepositAssetsDest__NotSet();

    error Shares__Init__EmptyName();

    error Shares__Init__EmptySymbol();

    error Shares__OnlyAdminOrOwner__Unauthorized();

    error Shares__OnlyDepositHandler__Unauthorized();

    error Shares__OnlyFeeHandler__Unauthorized();

    error Shares__OnlyRedeemHandler__Unauthorized();

    error Shares__RemoveAdmin__AlreadyRemoved();

    error Shares__RemoveAllowedHolder__AlreadyRemoved();

    error Shares__RemoveDepositHandler__AlreadyRemoved();

    error Shares__RemoveRedeemHandler__AlreadyRemoved();

    error Shares__SetValueAsset__Empty();

    error Shares__ValidateTransferRecipient__NotAllowed();

    error Shares__WithdrawAssetTo__Unauthorized();

    //==================================================================================================================
    // Modifiers
    //==================================================================================================================

    modifier onlyAdminOrOwner() {
        require(isAdminOrOwner(msg.sender), Shares__OnlyAdminOrOwner__Unauthorized());

        _;
    }

    modifier onlyDepositHandler() {
        require(isDepositHandler(msg.sender), Shares__OnlyDepositHandler__Unauthorized());

        _;
    }

    modifier onlyFeeHandler() {
        require(msg.sender == getFeeHandler(), Shares__OnlyFeeHandler__Unauthorized());

        _;
    }

    modifier onlyRedeemHandler() {
        require(isRedeemHandler(msg.sender), Shares__OnlyRedeemHandler__Unauthorized());

        _;
    }

    //==================================================================================================================
    // Constructor
    //==================================================================================================================

    constructor() {
        StorageHelpersLib.verifyErc7201LocationForId({
            _location: SHARES_STORAGE_LOCATION,
            _id: SHARES_STORAGE_LOCATION_ID
        });
    }

    //==================================================================================================================
    // Initialize
    //==================================================================================================================

    /// @notice Initializer for the contract
    /// @param _owner The account to be the "owner" role
    /// @param _name The name of the Shares token (ERC20)
    /// @param _symbol The symbol of the Shares token (ERC20)
    /// @param _valueAsset The representation of the asset of account for valuations (e.g., USD)
    function init(address _owner, string memory _name, string memory _symbol, bytes32 _valueAsset)
        external
        initializer
    {
        require(bytes(_name).length > 0, Shares__Init__EmptyName());
        require(bytes(_symbol).length > 0, Shares__Init__EmptySymbol());

        __ERC20_init({name_: _name, symbol_: _symbol});
        __Ownable_init({initialOwner: _owner});

        __setValueAsset(_valueAsset);
    }

    //==================================================================================================================
    // ERC20 overrides
    //==================================================================================================================

    /// @notice Standard ERC20 transfer of shares
    function transfer(address _to, uint256 _amount) public override returns (bool) {
        __validateSharesTransfer({_from: msg.sender, _to: _to, _amount: _amount});

        return super.transfer(_to, _amount);
    }

    /// @notice Standard ERC20 transferFrom of shares
    function transferFrom(address _from, address _to, uint256 _amount) public override returns (bool) {
        __validateSharesTransfer({_from: _from, _to: _to, _amount: _amount});

        return super.transferFrom(_from, _to, _amount);
    }

    function __validateSharesTransfer(address _from, address _to, uint256 _amount) internal {
        address sharesTransferValidator = getSharesTransferValidator();

        if (sharesTransferValidator != address(0)) {
            ISharesTransferValidator(sharesTransferValidator).validateSharesTransfer({
                _from: _from,
                _to: _to,
                _amount: _amount
            });
        }
    }

    //==================================================================================================================
    // ERC20-like extensions (access: mixed)
    //==================================================================================================================

    /// @notice Unvalidated transfer() for trusted handlers.
    /// @dev Any validation of the recipient must be done by the calling contract.
    /// Needed for, e.g.,:
    /// - Shares distribution from async deposit handler
    /// - Redeem request cancellation from async redeem handler
    function authTransfer(address _to, uint256 _amount) external {
        require(isDepositHandler(msg.sender) || isRedeemHandler(msg.sender), Shares__AuthTransfer__Unauthorized());

        _transfer(msg.sender, _to, _amount);
    }

    /// @notice Unvalidated transferFrom() for trusted handlers.
    /// @dev Any validation of the recipient must be done by the calling contract.
    /// Needed for, e.g.,:
    /// - Approval-less redemption from async redeem handler
    /// - Forced transfers via redeem handler (sometimes a compliance requirement)
    function authTransferFrom(address _from, address _to, uint256 _amount) external onlyRedeemHandler {
        _transfer(_from, _to, _amount);
    }

    //==================================================================================================================
    // Config (access: owner)
    //==================================================================================================================

    function addAdmin(address _admin) external onlyOwner {
        require(!isAdmin(_admin), Shares__AddAdmin__AlreadyAdded());

        SharesStorage storage $ = __getSharesStorage();
        $.isAdmin[_admin] = true;

        emit AdminAdded(_admin);
    }

    function removeAdmin(address _admin) external onlyOwner {
        require(isAdmin(_admin), Shares__RemoveAdmin__AlreadyRemoved());

        SharesStorage storage $ = __getSharesStorage();
        $.isAdmin[_admin] = false;

        emit AdminRemoved(_admin);
    }

    //==================================================================================================================
    // Config (access: admin or owner)
    //==================================================================================================================

    // SYSTEM CONTRACTS

    function addDepositHandler(address _handler) external onlyAdminOrOwner {
        require(!isDepositHandler(_handler), Shares__AddDepositHandler__AlreadyAdded());

        SharesStorage storage $ = __getSharesStorage();
        $.isDepositHandler[_handler] = true;

        emit DepositHandlerAdded(_handler);
    }

    function addRedeemHandler(address _handler) external onlyAdminOrOwner {
        require(!isRedeemHandler(_handler), Shares__AddRedeemHandler__AlreadyAdded());

        SharesStorage storage $ = __getSharesStorage();
        $.isRedeemHandler[_handler] = true;

        emit RedeemHandlerAdded(_handler);
    }

    function removeDepositHandler(address _handler) external onlyAdminOrOwner {
        require(isDepositHandler(_handler), Shares__RemoveDepositHandler__AlreadyRemoved());

        SharesStorage storage $ = __getSharesStorage();
        $.isDepositHandler[_handler] = false;

        emit DepositHandlerRemoved(_handler);
    }

    function removeRedeemHandler(address _handler) external onlyAdminOrOwner {
        require(isRedeemHandler(_handler), Shares__RemoveRedeemHandler__AlreadyRemoved());

        SharesStorage storage $ = __getSharesStorage();
        $.isRedeemHandler[_handler] = false;

        emit RedeemHandlerRemoved(_handler);
    }

    function setFeeHandler(address _feeHandler) external onlyAdminOrOwner {
        SharesStorage storage $ = __getSharesStorage();
        $.feeHandler = _feeHandler;

        emit FeeHandlerSet(_feeHandler);
    }

    /// @dev Can set to any non-existent, arbitrary address to make Shares non-transferrable
    function setSharesTransferValidator(address _sharesTransferValidator) external onlyAdminOrOwner {
        SharesStorage storage $ = __getSharesStorage();
        $.sharesTransferValidator = _sharesTransferValidator;

        emit SharesTransferValidatorSet(_sharesTransferValidator);
    }

    function setValuationHandler(address _valuationHandler) external onlyAdminOrOwner {
        SharesStorage storage $ = __getSharesStorage();
        $.valuationHandler = _valuationHandler;

        emit ValuationHandlerSet(_valuationHandler);
    }

    // HELPERS

    function __setValueAsset(bytes32 _valueAsset) internal {
        require(_valueAsset != "", Shares__SetValueAsset__Empty());

        SharesStorage storage $ = __getSharesStorage();
        $.valueAsset = _valueAsset;

        emit ValueAssetSet(_valueAsset);
    }

    //==================================================================================================================
    // Valuation
    //==================================================================================================================

    /// @notice Returns the latest share price and its timestamp
    /// @return price_ The share price
    /// @return timestamp_ The timestamp of the share price
    /// @dev 18-decimals of precision
    function sharePrice() external view returns (uint256 price_, uint256 timestamp_) {
        return IValuationHandler(getValuationHandler()).getSharePrice();
    }

    /// @notice Returns the latest share value and its timestamp
    /// @return value_ The share value
    /// @return timestamp_ The timestamp of the share value
    /// @dev 18-decimals of precision
    function shareValue() external view returns (uint256 value_, uint256 timestamp_) {
        return IValuationHandler(getValuationHandler()).getShareValue();
    }

    //==================================================================================================================
    // Shares issuance and asset transfers
    //==================================================================================================================

    /// @dev No general burn() function is exposed, in order to guarantee constant supply during share value updates

    // DEPOSIT FLOW

    /// @dev Callable by: DepositHandler
    function mintFor(address _to, uint256 _sharesAmount) external onlyDepositHandler {
        _mint(_to, _sharesAmount);
    }

    // REDEEM FLOW

    /// @dev Callable by: RedeemHandler
    function burnFor(address _from, uint256 _sharesAmount) external onlyRedeemHandler {
        _burn(_from, _sharesAmount);
    }

    // ASSET TRANSFERS

    /// @dev Callable by: admin, RedeemHandler, FeeHandler
    function withdrawAssetTo(address _asset, address _to, uint256 _amount) external {
        require(
            isAdminOrOwner(msg.sender) || isRedeemHandler(msg.sender) || msg.sender == getFeeHandler(),
            Shares__WithdrawAssetTo__Unauthorized()
        );

        IERC20(_asset).safeTransfer(_to, _amount);

        emit AssetWithdrawn({caller: msg.sender, asset: _asset, to: _to, amount: _amount});
    }

    //==================================================================================================================
    // Misc
    //==================================================================================================================

    /// @notice Returns whether an account has either an "admin" or "owner" role
    function isAdminOrOwner(address _who) public view returns (bool) {
        return _who == owner() || isAdmin(_who);
    }

    //==================================================================================================================
    // State getters
    //==================================================================================================================

    /// @notice Returns the contract that handles fees logic
    function getFeeHandler() public view returns (address) {
        return __getSharesStorage().feeHandler;
    }

    /// @notice Returns the contract that validates shares transfers
    function getSharesTransferValidator() public view returns (address) {
        return __getSharesStorage().sharesTransferValidator;
    }

    /// @notice Returns the contract the handles valuation logic
    function getValuationHandler() public view returns (address) {
        return __getSharesStorage().valuationHandler;
    }

    /// @notice Returns the encoded representation of the asset of account (e.g., USD, ETH)
    function getValueAsset() public view returns (bytes32) {
        return __getSharesStorage().valueAsset;
    }

    /// @notice Returns whether an account has an "admin" role
    function isAdmin(address _who) public view returns (bool) {
        return __getSharesStorage().isAdmin[_who];
    }

    /// @notice Returns whether an account is an allowed deposit handler
    function isDepositHandler(address _who) public view returns (bool) {
        return __getSharesStorage().isDepositHandler[_who];
    }

    /// @notice Returns whether an account is an allowed redeem handler
    function isRedeemHandler(address _who) public view returns (bool) {
        return __getSharesStorage().isRedeemHandler[_who];
    }
}

src/utils/StorageHelpersLib.sol

// SPDX-License-Identifier: BUSL-1.1

/*
    This file is part of the Onyx Protocol.

    (c) Enzyme Foundation <[email protected]>

    For the full license information, please view the LICENSE
    file that was distributed with this source code.
*/

pragma solidity ^0.8.0;

/// @title StorageHelpersLib Library
/// @author Enzyme Foundation <[email protected]>
/// @notice Common utility functions for handling storage
library StorageHelpersLib {
    error StorageHelpersLib__VerifyErc7201Location__Mismatch();

    /// @dev https://eips.ethereum.org/EIPS/eip-7201
    function deriveErc7201Location(string memory _id) internal pure returns (bytes32) {
        return keccak256(abi.encode(uint256(keccak256(bytes(string.concat("enzyme.", _id)))) - 1))
            & ~bytes32(uint256(0xff));
    }

    function verifyErc7201LocationForId(bytes32 _location, string memory _id) internal pure {
        require(_location == deriveErc7201Location(_id), StorageHelpersLib__VerifyErc7201Location__Mismatch());
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.