Collector

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "src/collectors/Collector.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;

import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";

import "../../src/interfaces/managers/IFeeManager.sol";
import "../../src/interfaces/managers/IRiskManager.sol";
import "../../src/interfaces/managers/IShareManager.sol";
import "../../src/interfaces/oracles/IOracle.sol";

import "../../src/interfaces/queues/IDepositQueue.sol";

import "../../src/interfaces/queues/IRedeemQueue.sol";
import "../../src/interfaces/queues/ISignatureQueue.sol";

import "../../src/libraries/TransferLibrary.sol";
import "../../src/vaults/Vault.sol";

import "./oracles/IPriceOracle.sol";

contract Collector is OwnableUpgradeable {
    struct Config {
        address baseAssetFallback;
        uint256 oracleUpdateInterval;
        uint256 redeemHandlingInterval;
    }

    struct Request {
        address queue;
        address asset;
        uint256 shares;
        uint256 assets;
        uint256 timestamp;
        uint256 eta;
    }

    struct QueueInfo {
        address queue;
        address asset;
        bool isDepositQueue;
        bool isPausedQueue;
        bool isSignatureQueue;
        uint256 pendingValue;
        uint256[] values;
    }

    struct Response {
        address vault;
        address baseAsset;
        address[] assets;
        uint8[] assetDecimals;
        uint256[] assetPrices;
        QueueInfo[] queues;
        uint256 totalLP;
        uint256 limitLP;
        uint256 accountLP;
        uint256 totalBase;
        uint256 limitBase;
        uint256 accountBase;
        uint256 lpPriceBase;
        uint256 totalUSD;
        uint256 limitUSD;
        uint256 accountUSD;
        uint256 lpPriceUSD;
        Request[] deposits;
        Request[] withdrawals;
        uint256 blockNumber;
        uint256 timestamp;
    }

    struct DepositParams {
        bool isDepositPossible;
        bool isDepositorWhitelisted;
        bool isMerkleProofRequired;
        address asset;
        uint256 shares;
        uint256 sharesUSDC;
        uint256 assets;
        uint256 assetsUSDC;
        uint256 eta;
    }

    struct WithdrawalParams {
        bool isWithdrawalPossible;
        address asset;
        uint256 shares;
        uint256 sharesUSDC;
        uint256 assets;
        uint256 assetsUSDC;
        uint256 eta;
    }

    address public immutable USD = address(bytes20(keccak256("usd-token-address")));
    address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

    IPriceOracle public oracle;
    uint256 public bufferSize;

    constructor() {
        _disableInitializers();
    }

    function initialize(address owner_, address oracle_) external initializer {
        __Ownable_init(owner_);
        oracle = IPriceOracle(oracle_);
        bufferSize = 256;
    }

    function setOracle(address oracle_) external onlyOwner {
        oracle = IPriceOracle(oracle_);
    }

    function setBufferSize(uint256 bufferSize_) external onlyOwner {
        bufferSize = bufferSize_;
    }

    function collect(address account, Vault vault, Config calldata config) public view returns (Response memory r) {
        r.vault = address(vault);
        r.blockNumber = block.number;
        r.timestamp = block.timestamp;

        IShareManager shareManager = vault.shareManager();
        IFeeManager feeManager = vault.feeManager();
        IRiskManager riskManager = vault.riskManager();
        IOracle vaultOracle = vault.oracle();

        r.baseAsset = feeManager.baseAsset(address(vault));
        if (r.baseAsset == address(0)) {
            r.baseAsset = config.baseAssetFallback;
        }

        {
            uint256 n = vaultOracle.supportedAssets();
            r.assets = new address[](n);
            r.assetDecimals = new uint8[](n);
            r.assetPrices = new uint256[](n);
            for (uint256 i = 0; i < n; i++) {
                r.assets[i] = vaultOracle.supportedAssetAt(i);
                if (r.assets[i] == ETH) {
                    r.assetDecimals[i] = 18;
                } else {
                    r.assetDecimals[i] = IERC20Metadata(r.assets[i]).decimals();
                }
                r.assetPrices[i] = oracle.priceX96(r.assets[i]);
            }
        }

        r.totalLP = shareManager.totalShares();
        r.accountLP = shareManager.sharesOf(account);

        {
            r.totalBase = Math.mulDiv(r.totalLP, 1 ether, vault.oracle().getReport(r.baseAsset).priceD18);
            if (r.totalBase > 0) {
                r.totalUSD = oracle.getValue(r.baseAsset, USD, r.totalBase);
            }
        }

        {
            IRiskManager.State memory vaultState = riskManager.vaultState();
            int256 remainingLimit = vaultState.limit - vaultState.balance;
            if (remainingLimit < 0) {
                remainingLimit = 0;
            }
            r.limitLP = uint256(remainingLimit) + r.totalLP;

            r.deposits = _collectDeposits(vault, account, config);
            r.withdrawals = _collectWithdrawals(vault, account, config);
        }

        if (r.totalLP > 0) {
            r.accountBase = Math.mulDiv(r.accountLP, r.totalBase, r.totalLP);
            r.accountUSD = Math.mulDiv(r.accountLP, r.totalUSD, r.totalLP);
            r.limitBase = Math.mulDiv(r.limitLP, r.totalBase, r.totalLP);
            r.limitUSD = oracle.getValue(r.baseAsset, USD, r.limitBase);
            r.lpPriceBase = Math.mulDiv(r.totalBase, 1 ether, r.totalLP);
            r.lpPriceUSD = oracle.getValue(r.baseAsset, USD, r.lpPriceBase);
        }

        {
            r.queues = new QueueInfo[](vault.getQueueCount());
            uint256 iterator = 0;
            uint256 assetCount = vault.getAssetCount();
            for (uint256 i = 0; i < assetCount; i++) {
                address asset = vault.assetAt(i);
                uint256 queueCount = vault.getQueueCount(asset);
                for (uint256 j = 0; j < queueCount; j++) {
                    address queue = vault.queueAt(asset, j);
                    r.queues[iterator] = QueueInfo({
                        queue: queue,
                        asset: asset,
                        isDepositQueue: vault.isDepositQueue(queue),
                        isPausedQueue: vault.isPausedQueue(queue),
                        isSignatureQueue: false,
                        pendingValue: 0,
                        values: new uint256[](0)
                    });
                    try ISignatureQueue(queue).consensus() returns (IConsensus) {
                        r.queues[iterator].isSignatureQueue = true;
                    } catch {
                        if (r.queues[iterator].isDepositQueue) {
                            r.queues[iterator].pendingValue = TransferLibrary.balanceOf(asset, queue);
                        } else {
                            (r.queues[iterator].pendingValue, r.queues[iterator].values) =
                                _collectRedeemQueueData(queue);
                        }
                    }
                    iterator++;
                }
            }
        }

        for (uint256 i = 0; i < r.queues.length; i++) {
            if (!r.queues[i].isDepositQueue) {
                continue;
            }
            address queue = r.queues[i].queue;
            address asset = r.queues[i].asset;
            uint256 pendingValue = TransferLibrary.balanceOf(asset, queue);
            if (pendingValue == 0) {
                continue;
            }
            if (asset != r.baseAsset) {
                r.totalBase += oracle.getValue(asset, r.baseAsset, pendingValue);
            } else {
                r.totalBase += pendingValue;
            }
        }
        if (r.totalBase > 0) {
            r.totalUSD = oracle.getValue(r.baseAsset, USD, r.totalBase);
        }
    }

    function _collectRedeemQueueData(address queue)
        internal
        view
        returns (uint256 pendingValue, uint256[] memory values)
    {
        uint256 limit;
        uint256 offset;
        (offset, limit,, pendingValue) = IRedeemQueue(queue).getState();
        values = new uint256[](limit - offset);
        for (uint256 i = 0; i < values.length; i++) {
            (values[i],) = IRedeemQueue(queue).batchAt(offset + i);
        }
    }

    function _collectDeposits(Vault vault, address account, Config calldata config)
        private
        view
        returns (Request[] memory requests)
    {
        requests = new Request[](vault.getQueueCount());
        uint256 iterator = 0;
        IOracle.SecurityParams memory securityParams = vault.oracle().securityParams();
        for (uint256 i = 0; i < vault.getAssetCount(); i++) {
            address asset = vault.assetAt(i);
            IOracle.DetailedReport memory report = vault.oracle().getReport(asset);
            for (uint256 j = 0; j < vault.getQueueCount(asset); j++) {
                address queue = vault.queueAt(asset, j);
                if (!vault.isDepositQueue(queue)) {
                    continue;
                }
                try ISignatureQueue(queue).consensus() {
                    continue;
                } catch {}
                (uint256 timestamp, uint256 assets) = IDepositQueue(queue).requestOf(account);
                if (assets == 0) {
                    continue;
                }
                requests[iterator] = Request({
                    queue: queue,
                    asset: asset,
                    shares: IDepositQueue(queue).claimableOf(account),
                    timestamp: timestamp,
                    assets: assets,
                    eta: 0
                });
                if (requests[iterator].shares == 0) {
                    requests[iterator].shares = Math.mulDiv(assets, report.priceD18, 1 ether);
                    requests[iterator].eta = _findNextTimestamp(
                        report.timestamp, timestamp, securityParams.depositInterval, config.oracleUpdateInterval
                    );
                }
                iterator++;
            }
        }
        assembly {
            mstore(requests, iterator)
        }
    }

    function _collectWithdrawals(Vault vault, address account, Config calldata config)
        private
        view
        returns (Request[] memory requests)
    {
        requests = new Request[](bufferSize);
        uint256 iterator = 0;
        IOracle.SecurityParams memory securityParams = vault.oracle().securityParams();
        for (uint256 i = 0; i < vault.getAssetCount(); i++) {
            address asset = vault.assetAt(i);
            IOracle.DetailedReport memory report = vault.oracle().getReport(asset);
            for (uint256 j = 0; j < vault.getQueueCount(asset); j++) {
                address queue = vault.queueAt(asset, j);
                if (vault.isDepositQueue(queue)) {
                    continue;
                }
                try ISignatureQueue(queue).consensus() {
                    continue;
                } catch {}
                IRedeemQueue.Request[] memory redeemRequests =
                    IRedeemQueue(queue).requestsOf(account, 0, requests.length);
                for (uint256 k = 0; k < redeemRequests.length; k++) {
                    requests[iterator] = Request({
                        queue: queue,
                        asset: asset,
                        shares: redeemRequests[k].shares,
                        assets: redeemRequests[k].assets,
                        timestamp: redeemRequests[k].timestamp,
                        eta: 0
                    });
                    if (redeemRequests[k].isClaimable) {} else if (redeemRequests[k].assets != 0) {
                        requests[iterator].eta = block.timestamp + config.redeemHandlingInterval;
                    } else {
                        requests[iterator].assets = Math.mulDiv(redeemRequests[k].shares, 1 ether, report.priceD18);
                        requests[iterator].eta = _findNextTimestamp(
                            report.timestamp,
                            redeemRequests[k].timestamp,
                            securityParams.redeemInterval,
                            config.oracleUpdateInterval
                        ) + config.redeemHandlingInterval;
                    }
                    iterator++;
                }
            }
        }
        assembly {
            mstore(requests, iterator)
        }
    }

    function _findNextTimestamp(
        uint256 reportTimestamp,
        uint256 requestTimestamp,
        uint256 oracleInterval,
        uint256 oracleUpdateInterval
    ) internal view returns (uint256) {
        uint256 latestOracleUpdate = reportTimestamp == 0 ? block.timestamp : reportTimestamp;
        uint256 minEligibleTimestamp = requestTimestamp + oracleInterval;
        uint256 delta = minEligibleTimestamp < latestOracleUpdate ? 0 : minEligibleTimestamp - latestOracleUpdate;
        return Math.max(
            block.timestamp + 1 hours,
            latestOracleUpdate
                + Math.max(oracleUpdateInterval, delta * (oracleUpdateInterval - 1) / oracleUpdateInterval)
        );
    }

    function collect(address user, address[] memory vaults, Config[] calldata configs)
        public
        view
        returns (Response[] memory responses)
    {
        responses = new Response[](vaults.length);
        for (uint256 i = 0; i < vaults.length; i++) {
            responses[i] = collect(user, Vault(payable(vaults[i])), configs[i]);
        }
    }

    function multiCollect(address[] calldata users, address[] calldata vaults, Config[] calldata configs)
        external
        view
        returns (Response[][] memory responses)
    {
        responses = new Response[][](users.length);
        for (uint256 i = 0; i < users.length; i++) {
            responses[i] = collect(users[i], vaults, configs);
        }
    }

    function getDepositParams(address queue, uint256 assets, address account, Config calldata config)
        external
        view
        returns (DepositParams memory r)
    {
        IDepositQueue depositQueue = IDepositQueue(queue);
        address vault = depositQueue.vault();
        r.asset = depositQueue.asset();
        IShareModule shareModule = IShareModule(vault);
        if (shareModule.isPausedQueue(queue)) {
            return r;
        }
        IOracle vaultOracle = shareModule.oracle();
        IOracle.DetailedReport memory report = vaultOracle.getReport(r.asset);
        if (report.isSuspicious || report.timestamp == 0) {
            return r;
        }
        r.isDepositPossible = true;
        {
            // Check whitelist
            IShareManager shareManager = shareModule.shareManager();
            if (!shareManager.accounts(account).canDeposit && shareManager.flags().hasWhitelist) {
                return r;
            }

            r.isMerkleProofRequired = shareManager.whitelistMerkleRoot() != bytes32(0);
            r.isDepositorWhitelisted = true;
        }

        r.assets = assets;
        r.assetsUSDC = oracle.getValue(r.asset, USD, r.assets);

        r.shares = Math.mulDiv(assets, report.priceD18, 1 ether);
        r.sharesUSDC = r.assetsUSDC;

        IFeeManager feeManager = shareModule.feeManager();
        if (feeManager.depositFeeD6() != 0) {
            r.shares -= feeManager.calculateDepositFee(r.shares);
            r.sharesUSDC -= feeManager.calculateDepositFee(r.sharesUSDC);
        }

        r.eta = _findNextTimestamp(
            report.timestamp, block.timestamp, vaultOracle.securityParams().depositInterval, config.oracleUpdateInterval
        );
    }

    function getWithdrawalParams(uint256 shares, address queue, Config calldata config)
        external
        view
        returns (WithdrawalParams memory r)
    {
        Vault vault = Vault(payable(IRedeemQueue(queue).vault()));

        r = WithdrawalParams({
            isWithdrawalPossible: !vault.isPausedQueue(queue),
            asset: IRedeemQueue(queue).asset(),
            shares: shares,
            sharesUSDC: 0,
            assets: 0,
            assetsUSDC: 0,
            eta: 0
        });
        if (!r.isWithdrawalPossible) {
            return r;
        }
        IOracle vaultOracle = vault.oracle();
        IOracle.DetailedReport memory report = vaultOracle.getReport(r.asset);
        if (report.isSuspicious || report.timestamp == 0) {
            return r;
        }

        r.assets = Math.mulDiv(r.shares, 1 ether, report.priceD18);
        r.assetsUSDC = oracle.getValue(r.asset, USD, r.assets);
        r.sharesUSDC = r.assetsUSDC;

        IFeeManager feeManager = vault.feeManager();
        if (feeManager.redeemFeeD6() != 0) {
            r.assets -= feeManager.calculateRedeemFee(r.assets);
            r.assetsUSDC -= feeManager.calculateRedeemFee(r.assetsUSDC);
        }

        r.eta = _findNextTimestamp(
            report.timestamp, block.timestamp, vaultOracle.securityParams().redeemInterval, config.oracleUpdateInterval
        );
    }
}
"
    },
    "lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol": {
      "content": "// 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/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
      "content": "// 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/utils/math/Math.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}
"
    },
    "src/interfaces/managers/IFeeManager.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;

import "../factories/IFactoryEntity.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";

/// @notice Interface for the FeeManager contract
/// @dev Handles deposit, redeem, performance, and protocol fees for vaults, and tracks per-vault price/timestamp states
interface IFeeManager is IFactoryEntity {
    /// @notice Thrown when a required address is zero
    error ZeroAddress();

    /// @notice Thrown when the sum of all fees exceeds 100% (1e6 in D6 precision)
    error InvalidFees(uint24 depositFeeD6, uint24 redeemFeeD6, uint24 performanceFeeD6, uint24 protocolFeeD6);

    /// @notice Thrown when trying to overwrite a vault's base asset that was already set
    error BaseAssetAlreadySet(address vault, address baseAsset);

    /// @notice Storage layout used internally by FeeManager
    struct FeeManagerStorage {
        address feeRecipient; // Address that collects all fee shares
        uint24 depositFeeD6; // Deposit fee in 6 decimals (e.g. 10000 = 1%)
        uint24 redeemFeeD6; // Redeem fee in 6 decimals
        uint24 performanceFeeD6; // Performance fee applied on price increase (6 decimals)
        uint24 protocolFeeD6; // Protocol fee applied over time (6 decimals annualized)
        mapping(address vault => uint256) timestamps; // Last update timestamp for protocol fee accrual
        mapping(address vault => uint256) minPriceD18; // Lowests price seen for performance fee trigger (price * assets = shares)
        mapping(address vault => address) baseAsset; // Base asset used to evaluate price-based fees
    }

    /// @notice Returns the current fee recipient address
    function feeRecipient() external view returns (address);

    /// @notice Returns the configured deposit fee (in D6 precision)
    function depositFeeD6() external view returns (uint24);

    /// @notice Returns the configured redeem fee (in D6 precision)
    function redeemFeeD6() external view returns (uint24);

    /// @notice Returns the configured performance fee (in D6 precision)
    function performanceFeeD6() external view returns (uint24);

    /// @notice Returns the configured protocol fee (in D6 precision per year)
    function protocolFeeD6() external view returns (uint24);

    /// @notice Returns the last recorded timestamp for a given vault (used for protocol fee accrual)
    function timestamps(address vault) external view returns (uint256);

    /// @notice Returns the last recorded min price for a vault's base asset (used for performance fee)
    function minPriceD18(address vault) external view returns (uint256);

    /// @notice Returns the base asset configured for a vault
    function baseAsset(address vault) external view returns (address);

    /// @notice Calculates the deposit fee in shares based on the amount
    /// @param amount Number of shares being deposited
    /// @return Fee in shares to be deducted
    function calculateDepositFee(uint256 amount) external view returns (uint256);

    /// @notice Calculates the redeem fee in shares based on the amount
    /// @param amount Number of shares being redeemed
    /// @return Fee in shares to be deducted
    function calculateRedeemFee(uint256 amount) external view returns (uint256);

    /// @notice Calculates the combined performance and protocol fee in shares
    /// @param vault Address of the vault
    /// @param asset Asset used for pricing
    /// @param priceD18 Current vault share price for the specific `asset` (price = shares / assets)
    /// @param totalShares Total shares of the vault
    /// @return shares Fee to be added in shares
    function calculateFee(address vault, address asset, uint256 priceD18, uint256 totalShares)
        external
        view
        returns (uint256 shares);

    /// @notice Sets the recipient address for all collected fees
    /// @param feeRecipient_ Address to receive fees
    function setFeeRecipient(address feeRecipient_) external;

    /// @notice Sets the global fee configuration (deposit, redeem, performance, protocol)
    /// @dev Total of all fees must be <= 1e6 (i.e. 100%)
    function setFees(uint24 depositFeeD6_, uint24 redeemFeeD6_, uint24 performanceFeeD6_, uint24 protocolFeeD6_)
        external;

    /// @notice Sets the base asset for a vault, required for performance fee calculation
    /// @dev Can only be set once per vault
    function setBaseAsset(address vault, address baseAsset_) external;

    /// @notice Updates the vault's state (min price and timestamp) based on asset price only if `asset` == `baseAssets[vault]`
    /// @dev Used by the vault to notify FeeManager of new price highs or protocol fee accrual checkpoints
    function updateState(address asset, uint256 priceD18) external;

    /// @notice Emitted when the fee recipient is changed
    event SetFeeRecipient(address indexed feeRecipient);

    /// @notice Emitted when the fee configuration is updated
    event SetFees(uint24 depositFeeD6, uint24 redeemFeeD6, uint24 performanceFeeD6, uint24 protocolFeeD6);

    /// @notice Emitted when a vault's base asset is set
    event SetBaseAsset(address indexed vault, address indexed baseAsset);

    /// @notice Emitted when the vault's min price or timestamp is updated
    event UpdateState(address indexed vault, address indexed asset, uint256 priceD18);
}
"
    },
    "src/interfaces/managers/IRiskManager.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;

import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";

import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";

import "../factories/IFactoryEntity.sol";

import "../modules/IACLModule.sol";
import "../modules/IShareModule.sol";
import "../modules/IVaultModule.sol";
import "../oracles/IOracle.sol";

/// @notice Interface for the RiskManager contract
/// @dev Handles vault and subvault balance limits, pending asset tracking, and asset permissioning
interface IRiskManager is IFactoryEntity {
    /// @notice Thrown when the caller lacks appropriate permission
    error Forbidden();

    /// @notice Thrown when a price report is flagged as suspicious, or has not been set yet.
    error InvalidReport();

    /// @notice Thrown when attempting to allow an already allowed asset
    error AlreadyAllowedAsset(address asset);

    /// @notice Thrown when attempting to disallow or use a non-allowed asset
    error NotAllowedAsset(address asset);

    /// @notice Thrown when a vault or subvault exceeds its configured limit
    error LimitExceeded(int256 newValue, int256 maxValue);

    /// @notice Thrown when a given address is not recognized as a valid subvault
    error NotSubvault(address subvault);

    /// @notice Thrown when a zero address is passed as a parameter
    error ZeroValue();

    /// @notice Tracks current and maximum balance for a vault or subvault
    struct State {
        int256 balance; // Current approximate shares held
        int256 limit; // Maximum allowable approximate shares
    }

    /// @notice Storage layout for RiskManager.
    struct RiskManagerStorage {
        address vault; // Address of the Vault associated with this risk manager.
        State vaultState; // Tracks the share balance and limit for the Vault.
        int256 pendingBalance;
        /// Cumulative approximate share balance from all pending requests in all deposit queues. Used to track unprocessed inflows.
        mapping(address asset => int256) pendingAssets; // Pending inflow amount per asset.
        mapping(address asset => int256) pendingShares; // Pending inflow amount in shares per asset converted by the last oracle report.
        mapping(address subvault => State) subvaultStates; // Share state tracking for each connected subvault.
        mapping(address subvault => EnumerableSet.AddressSet) allowedAssets; // List of assets that each subvault is allowed to interact with.
    }

    /// @notice Reverts if the given subvault is not valid for the vault
    function requireValidSubvault(address vault_, address subvault) external view;

    /// @notice Returns the address of the Vault
    function vault() external view returns (address);

    /// @notice Returns the approximate share balance and the share limit limit of the vault.
    function vaultState() external view returns (State memory);

    /// @notice Returns the pending share balance across all assets and deposit queues.
    function pendingBalance() external view returns (int256);

    /// @notice Returns the pending asset value for a specific asset
    function pendingAssets(address asset) external view returns (int256);

    /// @notice Returns the pending shares equivalent of a specific asset converted by the last oracle report for the given asset.
    function pendingShares(address asset) external view returns (int256);

    /// @notice Returns the approximate balance and the limit of a specific subvault
    function subvaultState(address subvault) external view returns (State memory);

    /// @notice Returns number of assets allowed for a given subvault
    function allowedAssets(address subvault) ext

Tags:
ERC20, ERC165, Multisig, Mintable, Burnable, Swap, Liquidity, Voting, Upgradeable, Multi-Signature, Factory, Oracle|addr:0x71e866be436ea5aca4ce11278ba0c2983bd0266b|verified:true|block:23741182|tx:0xb41ba3043b1e5ff711796131ab0fafe10d6b982ff25ba3cd8bdaef1ea1f160dc|first_check:1762444007

Submitted on: 2025-11-06 16:46:49

Comments

Log in to comment.

No comments yet.