Skip to content
Verified contractPartial

Allocator

Address0x8e7a201c057eba5b9dfe261edd015cf82770e8e5
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.35

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.35+commit.47b9dedd
Language
solidity
Optimization
Yes, 200 runs
EVM version
osaka
Via IR
yes
License
Not stated
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,382,788
Creation transaction
0xd676d3e5b4…7e24ccdfe1

src/allocator/Allocator.sol


pragma solidity ^0.8.20;

import {IERC20} from "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol";

import {IAllocator} from "../interfaces/IAllocator.sol";
import {IAdapterSwap} from "../interfaces/IAdapterSwap.sol";
import {IHypercoreTradingAdapter} from "../interfaces/IHypercoreTradingAdapter.sol";
import {IOwlVault} from "../interfaces/IOwlVault.sol";
import {IStrategyAdapter} from "../interfaces/IStrategyAdapter.sol";
import {IValuationGuard} from "../interfaces/IValuationGuard.sol";
import {IPermissionManager} from "../interfaces/IPermissionManager.sol";
import {Roles} from "../libraries/Roles.sol";

interface IHyperliquidAdapterExt {
    function addApiWallet(address agent, string calldata name) external;
}

interface IOndoAdapterExt {
    function registerToken(address token, address pool) external;
    function unregisterToken(address token) external;
    function setTwapWindow(uint32 window) external;
    function registerTokens(address[] calldata tokens, address[] calldata pools) external;
    function unregisterTokens(address[] calldata tokens) external;
}

contract Allocator is IAllocator, ReentrancyGuard {
    using SafeERC20 for IERC20;

    uint256 public constant MAX_ADAPTERS = 100;

    address public deployer;

    address public vault;
    address public accountingEngine;
    IPermissionManager public permissionManager;

    function init() external {
        require(deployer == address(0), "Already initialized");
        deployer = msg.sender;
    }

    mapping(address => bool) public override isAdapterWhitelisted;
    mapping(address => bool) private isAdapterKnown;
    address[] private knownAdapters;

    mapping(address => uint256) public override adapterAssets;

    bool public paused;

    bool public initialized;

    modifier onlyAdminOrAllocator() {
        require(
            permissionManager.hasRole(Roles.ADMIN, msg.sender) || permissionManager.hasRole(Roles.ALLOCATOR, msg.sender),
            "Not admin or allocator"
        );
        _;
    }

    modifier onlyTraderOrAdminOrAllocator() {
        require(
            permissionManager.hasRole(Roles.TRADER, msg.sender) || permissionManager.hasRole(Roles.ADMIN, msg.sender)
                || permissionManager.hasRole(Roles.ALLOCATOR, msg.sender),
            "Not trader or admin or allocator"
        );
        _;
    }

    modifier onlyEmergency() {
        require(
            permissionManager.hasRole(Roles.EMERGENCY, msg.sender) || permissionManager.hasRole(Roles.ADMIN, msg.sender),
            "Not emergency or admin"
        );
        _;
    }

    modifier onlyAdmin() {
        require(permissionManager.hasRole(Roles.ADMIN, msg.sender), "Not admin");
        _;
    }

    modifier whenNotPaused() {
        require(!paused, "Allocator paused");
        _;
    }

    function deployToAdapter(address adapter, uint256 amount)
        external
        override
        nonReentrant
        onlyAdminOrAllocator
        whenNotPaused
    {
        require(isAdapterWhitelisted[adapter], "Adapter not whitelisted");

        IERC20 token = IERC20(IStrategyAdapter(adapter).asset());
        require(token == IERC20(IOwlVault(vault).asset()), "Token mismatch");
        IOwlVault(vault).deployToAdapter(amount);
        token.forceApprove(adapter, amount);
        IStrategyAdapter(adapter).deposit(token, amount);
        token.forceApprove(adapter, 0);

        adapterAssets[adapter] += amount;
        emit AdapterDeployed(adapter, amount);
    }

    function withdrawFromAdapter(address adapter, uint256 amount) external override nonReentrant onlyAdminOrAllocator {
        require(isAdapterKnown[adapter], "Adapter not known");
        _withdrawFromAdapter(adapter, amount);
    }

    function withdrawAvailableFromAdapter(address adapter)
        external
        override
        nonReentrant
        onlyAdminOrAllocator
        returns (uint256 recoveredAmount)
    {
        require(isAdapterKnown[adapter], "Adapter not known");
        return _withdrawAvailableFromAdapter(adapter);
    }

    function placeOrder(address adapter, IHypercoreTradingAdapter.OrderRequest calldata order)
        external
        override
        onlyAdminOrAllocator
        whenNotPaused
    {
        require(isAdapterWhitelisted[adapter], "Adapter not whitelisted");

        IHypercoreTradingAdapter(adapter).placeOrder(order);

        emit OrderPlaced(adapter, order.marketId, order.isBuy, order.size, order.limitPrice, order.cloid);
    }

    function cancelOrder(address adapter, IHypercoreTradingAdapter.CancelRequest calldata cancel)
        external
        override
        onlyAdminOrAllocator
    {
        require(isAdapterKnown[adapter], "Adapter not known");

        IHypercoreTradingAdapter(adapter).cancelOrder(cancel);

        emit OrderCancelled(adapter, cancel.marketId, cancel.orderId);
    }

    function addAdapterPerpDex(address adapter, uint32 dex) external override onlyAdminOrAllocator {
        require(isAdapterKnown[adapter], "Adapter not known");

        IHypercoreTradingAdapter(adapter).addPerpDex(dex);

        emit AdapterPerpDexAdded(adapter, dex);
    }

    function removeAdapterPerpDex(address adapter, uint32 dex) external override onlyAdminOrAllocator {
        require(isAdapterKnown[adapter], "Adapter not known");

        IHypercoreTradingAdapter(adapter).removePerpDex(dex);

        emit AdapterPerpDexRemoved(adapter, dex);
    }

    function reportAdapterActiveSpotMarkets(address adapter, uint32[] calldata marketIds)
        external
        override
        onlyAdminOrAllocator
    {
        require(isAdapterKnown[adapter], "Adapter not known");

        IHypercoreTradingAdapter(adapter).reportActiveSpotMarkets(marketIds);

        emit AdapterActiveSpotMarketsReported(adapter, marketIds);
    }

    function pruneAdapterZeroBalanceSpotMarkets(address adapter)
        external
        override
        onlyAdminOrAllocator
        returns (uint256 removed)
    {
        require(isAdapterKnown[adapter], "Adapter not known");

        removed = IHypercoreTradingAdapter(adapter).pruneZeroBalanceSpotMarkets();

        emit AdapterZeroBalanceSpotMarketsPruned(adapter);
    }

    function pruneAdapterZeroBalanceSpotMarkets(address adapter, uint32[] calldata marketIds)
        external
        override
        onlyAdminOrAllocator
        returns (uint256 removed)
    {
        require(isAdapterKnown[adapter], "Adapter not known");

        removed = IHypercoreTradingAdapter(adapter).pruneZeroBalanceSpotMarkets(marketIds);

        emit AdapterZeroBalanceSpotMarketsPruned(adapter);
    }

    function registerAdapterToken(address adapter, address token, address pool)
        external
        onlyAdminOrAllocator
        whenNotPaused
    {
        require(isAdapterWhitelisted[adapter], "Adapter not whitelisted");
        IOndoAdapterExt(adapter).registerToken(token, pool);
        emit AdapterTokenRegistered(adapter, token, pool);
    }

    function registerAdapterTokens(address adapter, address[] calldata tokens, address[] calldata pools)
        external
        onlyAdminOrAllocator
        whenNotPaused
    {
        require(isAdapterWhitelisted[adapter], "Adapter not whitelisted");
        IOndoAdapterExt(adapter).registerTokens(tokens, pools);
        emit AdapterTokensRegistered(adapter, tokens);
    }

    function unregisterAdapterToken(address adapter, address token) external onlyAdminOrAllocator whenNotPaused {
        require(isAdapterWhitelisted[adapter], "Adapter not whitelisted");
        IOndoAdapterExt(adapter).unregisterToken(token);
        emit AdapterTokenUnregistered(adapter, token);
    }

    function unregisterAdapterTokens(address adapter, address[] calldata tokens)
        external
        onlyAdminOrAllocator
        whenNotPaused
    {
        require(isAdapterWhitelisted[adapter], "Adapter not whitelisted");
        IOndoAdapterExt(adapter).unregisterTokens(tokens);
        emit AdapterTokensUnregistered(adapter, tokens);
    }

    function setAdapterTwapWindow(address adapter, uint32 window) external override onlyAdminOrAllocator whenNotPaused {
        require(isAdapterWhitelisted[adapter], "Adapter not whitelisted");
        IOndoAdapterExt(adapter).setTwapWindow(window);
        emit AdapterTwapWindowUpdated(adapter, window);
    }

    function transferAdapterPerpToSpot(address adapter, uint64 ntl) external override onlyAdminOrAllocator {
        require(isAdapterKnown[adapter], "Adapter not known");

        IHypercoreTradingAdapter(adapter).transferPerpToSpot(ntl);

        emit AdapterTransferredPerpToSpot(adapter, ntl);
    }

    function transferAdapterPerpToSpot(address adapter, uint32 marketId, uint64 ntl)
        external
        override
        onlyAdminOrAllocator
    {
        require(isAdapterKnown[adapter], "Adapter not known");

        IHypercoreTradingAdapter(adapter).transferPerpToSpot(marketId, ntl);

        emit AdapterTransferredPerpToSpotMarket(adapter, marketId, ntl);
    }

    function transferAdapterSpotToPerp(address adapter, uint64 ntl) external override onlyAdminOrAllocator {
        require(isAdapterKnown[adapter], "Adapter not known");

        IHypercoreTradingAdapter(adapter).transferSpotToPerp(ntl);

        emit AdapterTransferredSpotToPerp(adapter, ntl);
    }

    function transferAdapterSpotToPerp(address adapter, uint32 marketId, uint64 ntl)
        external
        override
        onlyAdminOrAllocator
    {
        require(isAdapterKnown[adapter], "Adapter not known");

        IHypercoreTradingAdapter(adapter).transferSpotToPerp(marketId, ntl);

        emit AdapterTransferredSpotToPerpMarket(adapter, marketId, ntl);
    }

    function bridgeAdapterToCoreSpot(address adapter, uint256 evmAmount) external override onlyAdminOrAllocator {
        require(isAdapterKnown[adapter], "Adapter not known");

        IHypercoreTradingAdapter(adapter).bridgeToCoreSpot(evmAmount);

        emit AdapterBridgedToCoreSpot(adapter, evmAmount);
    }

    function bridgeAdapterSpotToEvm(address adapter, uint64 coreAmount) external override onlyAdminOrAllocator {
        require(isAdapterKnown[adapter], "Adapter not known");

        IHypercoreTradingAdapter(adapter).bridgeSpotToEvm(coreAmount);

        emit AdapterBridgedSpotToEvm(adapter, coreAmount);
    }

    function swapAdapterToken(address adapter, IAllocator.AdapterSwapParams calldata params)
        external
        override
        onlyTraderOrAdminOrAllocator
        whenNotPaused
        nonReentrant
        returns (uint256 amountOut)
    {
        require(isAdapterWhitelisted[adapter], "Adapter not whitelisted");

        amountOut = IAdapterSwap(adapter)
            .swap(params.orderId, params.tokenIn, params.tokenOut, params.amountIn, params.minAmountOut, params.fee);

        emit AdapterSwapExecuted(adapter, params.orderId, params.tokenIn, params.amountIn, amountOut);
    }

    function swapAdapterPath(address adapter, IAllocator.AdapterSwapPathParams calldata params)
        external
        override
        onlyTraderOrAdminOrAllocator
        whenNotPaused
        nonReentrant
        returns (uint256 amountOut)
    {
        require(isAdapterWhitelisted[adapter], "Adapter not whitelisted");

        amountOut = IAdapterSwap(adapter).swapPath(params.orderId, params.path, params.amountIn, params.minAmountOut);

        emit AdapterSwapExecuted(adapter, params.orderId, address(bytes20(params.path[0:20])), params.amountIn, amountOut);
    }

    function setAdapterMarketAllowed(address adapter, uint32 marketId, bool allowed)
        external
        override
        onlyAdminOrAllocator
    {
        require(isAdapterKnown[adapter], "Adapter not known");

        IHypercoreTradingAdapter(adapter).setAllowedMarket(marketId, allowed);

        emit AdapterMarketAllowedSet(adapter, marketId, allowed);
    }

    function setAdapterMarketsAllowed(address adapter, uint32[] calldata marketIds, bool allowed)
        external
        override
        onlyAdminOrAllocator
    {
        require(isAdapterKnown[adapter], "Adapter not known");

        IHypercoreTradingAdapter(adapter).setAllowedMarkets(marketIds, allowed);

        for (uint256 i = 0; i < marketIds.length; i++) {
            emit AdapterMarketAllowedSet(adapter, marketIds[i], allowed);
        }
    }

    function setAdapterAccountAbstraction(address adapter, uint8 mode) external override onlyAdminOrAllocator {
        require(isAdapterKnown[adapter], "Adapter not known");

        IHypercoreTradingAdapter(adapter).setAccountAbstraction(mode);

        emit AdapterAccountAbstractionSet(adapter, mode);
    }

    function totalAdapterAssets() external view override returns (uint256 total) {
        uint256 adapterCount = knownAdapters.length;
        for (uint256 i = 0; i < adapterCount; i++) {
            if (isAdapterWhitelisted[knownAdapters[i]]) {
                total += IStrategyAdapter(knownAdapters[i]).totalAssets();
            }
        }
    }

    function entryValuationBroken() external view override returns (bool) {
        uint256 adapterCount = knownAdapters.length;
        for (uint256 i = 0; i < adapterCount; i++) {
            address adapter = knownAdapters[i];
            if (!isAdapterWhitelisted[adapter]) continue;
            (bool ok, bytes memory ret) =
                adapter.staticcall(abi.encodeWithSelector(IValuationGuard.valuationBroken.selector));
            if (ok && ret.length >= 32 && abi.decode(ret, (bool))) return true;
        }
        return false;
    }

    function pause() external override onlyEmergency {
        paused = true;
    }

    function unpause() external override onlyAdminOrAllocator {
        paused = false;
    }

    function setPermissionManager(address pm) external {
        require(pm != address(0), "Zero address");
        if (address(permissionManager) != address(0)) {
            require(permissionManager.hasRole(Roles.ADMIN, msg.sender), "Not admin");
        } else {
            require(msg.sender == deployer, "Not deployer");
        }
        address oldPm = address(permissionManager);
        permissionManager = IPermissionManager(pm);
        emit PermissionManagerUpdated(oldPm, pm);
    }

    function addAdapter(address adapter) external override onlyAdmin {
        if (!isAdapterKnown[adapter]) {
            require(knownAdapters.length < MAX_ADAPTERS, "Max adapters");
            isAdapterKnown[adapter] = true;
            knownAdapters.push(adapter);
        }
        isAdapterWhitelisted[adapter] = true;
        emit AdapterAdded(adapter);
    }

    function removeAdapter(address adapter, bool acceptRemainingFunds) external override onlyAdmin {
        require(isAdapterKnown[adapter], "Adapter not known");

        uint256 remaining;
        bool unreadable;
        try IStrategyAdapter(adapter).totalAssets() returns (uint256 v) {
            remaining = v;
        } catch {
            unreadable = true;
        }
        if (remaining > 0 || unreadable) {
            require(acceptRemainingFunds, "Adapter still funded; pass true to accept");
        }
        isAdapterWhitelisted[adapter] = false;
        emit AdapterRemoved(adapter, remaining);
    }

    function addAdapterApiWallet(address adapter, address agent, string calldata name)
        external
        override
        onlyAdminOrAllocator
    {
        require(isAdapterKnown[adapter], "Adapter not known");
        IHyperliquidAdapterExt(adapter).addApiWallet(agent, name);
    }

    function setAdapterAllocator(address adapter, address newAllocator) external override onlyAdmin {
        require(isAdapterKnown[adapter], "Adapter not known");
        require(newAllocator != address(0), "Zero allocator");
        IStrategyAdapter(adapter).setAllocator(newAllocator);
        emit AdapterAllocatorUpdated(adapter, newAllocator);
    }

    function setVault(address _vault) external override onlyAdmin {
        require(_vault != address(0), "Zero address");
        address oldVault = vault;
        vault = _vault;
        emit VaultUpdated(oldVault, _vault);
    }

    function setAccountingEngine(address engine) external override onlyAdmin {
        require(engine != address(0), "Zero address");
        address oldEngine = accountingEngine;
        accountingEngine = engine;
        emit AccountingEngineUpdated(oldEngine, engine);
    }

    struct InitConfig {
        address permissionManager;
        address vault;
        address accountingEngine;
        address adapter;
    }

    function initialize(InitConfig calldata cfg) external {
        require(!initialized, "Already initialized");
        if (address(permissionManager) != address(0)) {
            require(permissionManager.hasRole(Roles.ADMIN, msg.sender), "Not admin");
        } else {
            require(msg.sender == deployer, "Only deployer");
        }
        if (cfg.permissionManager != address(0)) {
            permissionManager = IPermissionManager(cfg.permissionManager);
        }
        if (cfg.vault != address(0)) vault = cfg.vault;
        if (cfg.accountingEngine != address(0)) accountingEngine = cfg.accountingEngine;
        if (cfg.adapter != address(0)) {
            if (!isAdapterKnown[cfg.adapter]) {
                isAdapterKnown[cfg.adapter] = true;
                knownAdapters.push(cfg.adapter);
            }
            isAdapterWhitelisted[cfg.adapter] = true;
        }
        initialized = true;
    }

    function _withdrawFromAdapter(address adapter, uint256 amount) internal {
        
        IERC20 token = IERC20(IStrategyAdapter(adapter).asset());
        require(token == IERC20(IOwlVault(vault).asset()), "Token mismatch");
        IStrategyAdapter(adapter).withdraw(token, amount);
        token.safeTransfer(vault, amount);
        IOwlVault(vault).increaseIdleBalance(amount);

        uint256 trackedAssets = adapterAssets[adapter];
        adapterAssets[adapter] = trackedAssets > amount ? trackedAssets - amount : 0;
        emit AdapterWithdrawn(adapter, amount);
    }

    function _withdrawAvailableFromAdapter(address adapter) internal returns (uint256 recoveredAmount) {
        recoveredAmount = IStrategyAdapter(adapter).availableLiquidity();
        if (recoveredAmount == 0) {
            return 0;
        }

        _withdrawFromAdapter(adapter, recoveredAmount);
    }
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

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

pragma solidity >=0.6.2;

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/contracts/interfaces/IERC165.sol

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

pragma solidity >=0.4.16;

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

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

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

pragma solidity >=0.4.16;

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

lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol

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

pragma solidity >=0.6.2;

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

/**
 * @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 */
interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);

    event Withdraw(
        address indexed sender,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function asset() external view returns (address assetTokenAddress);

    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);

    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address receiver) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Deposit `assets` underlying tokens and send the corresponding number of vault shares (`shares`) to `receiver`.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address receiver) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly `shares` vault shares to `receiver` in exchange for `assets` underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(uint256 shares, address receiver) external returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address owner) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address owner) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}

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

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

pragma solidity >=0.4.16;

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

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

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

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

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

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

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

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

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

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

pragma solidity >=0.6.2;

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/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.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 {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @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 {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 relies 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 relies 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}.
     * Oppositely, 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 `token.transfer(to, value)` call, 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 to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 *
 * IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
 * by the {ReentrancyGuardTransient} variant in v6.0.
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuard {
    using StorageSlot for bytes32;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

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

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

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

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

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

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

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

pragma solidity >=0.4.16;

/**
 * @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/interfaces/IAdapterSwap.sol


pragma solidity ^0.8.20;

interface IAdapterSwap {
    function swap(
        uint256 orderId,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOut,
        uint24 fee
    ) external returns (uint256 amountOut);

    function swapPath(
        uint256 orderId,
        bytes calldata path,
        uint256 amountIn,
        uint256 minAmountOut
    ) external returns (uint256 amountOut);
}

src/interfaces/IAllocator.sol


pragma solidity ^0.8.20;

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

interface IAllocator {

    struct AdapterSwapParams {
        uint256 orderId;
        address tokenIn;
        address tokenOut;
        uint256 amountIn;
        uint256 minAmountOut;
        uint24 fee;
    }

    function deployToAdapter(address adapter, uint256 amount) external;

    function withdrawFromAdapter(address adapter, uint256 amount) external;

    function withdrawAvailableFromAdapter(address adapter) external returns (uint256 recoveredAmount);

    function placeOrder(
        address adapter,
        IHypercoreTradingAdapter.OrderRequest calldata order
    ) external;

    function cancelOrder(
        address adapter,
        IHypercoreTradingAdapter.CancelRequest calldata cancel
    ) external;

    function setAdapterMarketAllowed(address adapter, uint32 marketId, bool allowed) external;

    function setAdapterMarketsAllowed(address adapter, uint32[] calldata marketIds, bool allowed) external;

    function setAdapterAccountAbstraction(address adapter, uint8 mode) external;

    function addAdapterPerpDex(address adapter, uint32 dex) external;

    function removeAdapterPerpDex(address adapter, uint32 dex) external;

    function reportAdapterActiveSpotMarkets(address adapter, uint32[] calldata marketIds) external;

    function pruneAdapterZeroBalanceSpotMarkets(address adapter) external returns (uint256 removed);

    function pruneAdapterZeroBalanceSpotMarkets(address adapter, uint32[] calldata marketIds)
        external
        returns (uint256 removed);

    function registerAdapterToken(address adapter, address token, address pool) external;

    function registerAdapterTokens(address adapter, address[] calldata tokens, address[] calldata pools) external;

    function unregisterAdapterToken(address adapter, address token) external;

    function unregisterAdapterTokens(address adapter, address[] calldata tokens) external;

    function setAdapterTwapWindow(address adapter, uint32 window) external;

    function transferAdapterPerpToSpot(address adapter, uint64 ntl) external;

    function transferAdapterPerpToSpot(address adapter, uint32 marketId, uint64 ntl) external;

    function transferAdapterSpotToPerp(address adapter, uint64 ntl) external;

    function transferAdapterSpotToPerp(address adapter, uint32 marketId, uint64 ntl) external;

    function bridgeAdapterToCoreSpot(address adapter, uint256 evmAmount) external;

    function bridgeAdapterSpotToEvm(address adapter, uint64 coreAmount) external;

    function swapAdapterToken(address adapter, AdapterSwapParams calldata params) external returns (uint256 amountOut);

    struct AdapterSwapPathParams {
        uint256 orderId;
        bytes path;
        uint256 amountIn;
        uint256 minAmountOut;
    }

    function swapAdapterPath(address adapter, AdapterSwapPathParams calldata params) external returns (uint256 amountOut);

    function adapterAssets(address adapter) external view returns (uint256);

    function totalAdapterAssets() external view returns (uint256);

    function entryValuationBroken() external view returns (bool);

    function pause() external;

    function unpause() external;

    function addAdapter(address adapter) external;

    function removeAdapter(address adapter, bool acceptRemainingFunds) external;

    function addAdapterApiWallet(address adapter, address agent, string calldata name) external;

    function setAdapterAllocator(address adapter, address newAllocator) external;

    function isAdapterWhitelisted(address adapter) external view returns (bool);

    function setPermissionManager(address pm) external;

    function setVault(address vault) external;

    function setAccountingEngine(address engine) external;

    event AdapterDeployed(address indexed adapter, uint256 amount);
    event AdapterWithdrawn(address indexed adapter, uint256 amount);

    event OrderPlaced(
        address indexed adapter, uint32 indexed marketId, bool isBuy, uint128 size, uint128 limitPrice, uint128 cloid
    );
    event OrderCancelled(address indexed adapter, uint32 indexed marketId, uint64 orderId);
    event AdapterMarketAllowedSet(address indexed adapter, uint32 indexed marketId, bool allowed);
    event AdapterAccountAbstractionSet(address indexed adapter, uint8 mode);
    event AdapterPerpDexAdded(address indexed adapter, uint32 dex);
    event AdapterPerpDexRemoved(address indexed adapter, uint32 dex);
    event AdapterActiveSpotMarketsReported(address indexed adapter, uint32[] marketIds);
    event AdapterZeroBalanceSpotMarketsPruned(address indexed adapter);
    
    event AdapterTokenRegistered(address indexed adapter, address indexed token, address indexed pool);
    event AdapterTokenUnregistered(address indexed adapter, address indexed token);
    event AdapterTokensRegistered(address indexed adapter, address[] tokens);
    event AdapterTokensUnregistered(address indexed adapter, address[] tokens);
    event AdapterTwapWindowUpdated(address indexed adapter, uint32 window);

    event AdapterTransferredPerpToSpot(address indexed adapter, uint64 ntl);
    event AdapterTransferredPerpToSpotMarket(address indexed adapter, uint32 marketId, uint64 ntl);
    event AdapterTransferredSpotToPerp(address indexed adapter, uint64 ntl);
    event AdapterTransferredSpotToPerpMarket(address indexed adapter, uint32 marketId, uint64 ntl);
    event AdapterBridgedToCoreSpot(address indexed adapter, uint256 evmAmount);
    event AdapterBridgedSpotToEvm(address indexed adapter, uint64 coreAmount);

    event AdapterSwapExecuted(address indexed adapter, uint256 indexed orderId, address indexed tokenIn, uint256 amountIn, uint256 amountOut);

    event AdapterAdded(address indexed adapter);
    event AdapterRemoved(address indexed adapter, uint256 remaining);
    event AdapterAllocatorUpdated(address indexed adapter, address newAllocator);
    event PermissionManagerUpdated(address oldPm, address newPm);
    event VaultUpdated(address oldVault, address newVault);
    event AccountingEngineUpdated(address oldEngine, address newEngine);
}

src/interfaces/IHypercoreTradingAdapter.sol


pragma solidity ^0.8.20;

interface IHypercoreTradingAdapter {
    struct OrderRequest {
        uint32 marketId;
        bool isBuy;
        uint128 size;
        uint128 limitPrice;
        bool reduceOnly;
        uint8 tif;

        uint128 cloid;
    }

    struct CancelRequest {
        uint32 marketId;
        uint64 orderId;
    }

    function bridgeToCoreSpot(uint256 evmAmount) external;

    function bridgeSpotToEvm(uint64 coreAmount) external;

    function transferSpotToPerp(uint64 ntl) external;

    function transferSpotToPerp(uint32 marketId, uint64 ntl) external;

    function transferPerpToSpot(uint64 ntl) external;

    function transferPerpToSpot(uint32 marketId, uint64 ntl) external;

    function quoteOrderNotional(OrderRequest calldata order) external view returns (uint256);

    function projectedMarketExposure(OrderRequest calldata order) external view returns (uint256);

    function addPerpDex(uint32 dex) external;

    function removePerpDex(uint32 dex) external;

    function reportActiveSpotMarkets(uint32[] calldata marketIds) external;

    function pruneZeroBalanceSpotMarkets() external returns (uint256 removed);

    function pruneZeroBalanceSpotMarkets(uint32[] calldata marketIds) external returns (uint256 removed);

    function placeOrder(OrderRequest calldata order) external;

    function cancelOrder(CancelRequest calldata cancel) external;

    function setAllowedMarket(uint32 marketId, bool allowed) external;

    function setAllowedMarkets(uint32[] calldata marketIds, bool allowed) external;

    function setAccountAbstraction(uint8 mode) external;
}

src/interfaces/IOwlVault.sol


pragma solidity ^0.8.20;

import {IERC4626} from "openzeppelin-contracts/contracts/interfaces/IERC4626.sol";

interface IOwlVault is IERC4626 {
    
    function FIRST_DEPOSIT_BRIDGE_FEE() external view returns (uint256);

    function requestWithdraw(
        uint256 shares,
        address receiver
    ) external returns (bytes32 requestId);

    function executeWithdraw(bytes32 requestId) external;

    function getWithdrawRequest(bytes32 requestId)
        external view
        returns (
            address receiver,
            uint256 shares,
            uint256 assets,
            uint256 requestTime
        );

    function getWithdrawRequester(bytes32 requestId) external view returns (address);

    function getUserWithdrawRequests(address user) external view returns (bytes32[] memory);

    function lockedSharesOf(address user) external view returns (uint256);

    function withdrawDelay() external view returns (uint256);

    function pause() external;

    function unpause() external;

    function paused() external view returns (bool);

    function setWithdrawDelay(uint256 newDelay) external;

    function setMinimumDeposit(uint256 newMinimum) external;

    function setDepositLockPeriod(uint256 newPeriod) external;

    function depositLockPeriod() external view returns (uint256);

    function depositUnlockTimeOf(address user) external view returns (uint256);

    function setShareTransferEnabled(bool enabled) external;

    function shareTransferEnabled() external view returns (bool);

    function idleBalance() external view returns (uint256);

    function bridgeFeeAccrued() external view returns (uint256);

    function increaseIdleBalance(uint256 amount) external;

    function sharePrice() external view returns (uint256);

    function setPermissionManager(address pm) external;

    function setAccountingEngine(address engine) external;

    function setAllocator(address allocator) external;

    function allocator() external view returns (address);

    function accountingEngine() external view returns (address);

    function deployToAdapter(uint256 amount) external;

    function mintFeeSharesBatch(address[] calldata recipients, uint256[] calldata shares) external;

    event WithdrawRequested(
        bytes32 indexed requestId,
        address indexed receiver,
        uint256 shares,
        uint256 assets,
        uint256 unlockTime,
        uint256 timestamp
    );
    event WithdrawExecuted(
        bytes32 indexed requestId,
        address indexed receiver,
        uint256 assets,
        uint256 exitFee,
        uint256 timestamp
    );
    event WithdrawDelayUpdated(uint256 oldDelay, uint256 newDelay);
    event MinimumDepositUpdated(uint256 oldMinimum, uint256 newMinimum);
    event DepositLockPeriodUpdated(uint256 oldPeriod, uint256 newPeriod);
    event ShareTransferEnabledUpdated(bool oldEnabled, bool newEnabled);
    event PermissionManagerUpdated(address oldPm, address newPm);
    event AccountingEngineUpdated(address oldEngine, address newEngine);
    event AllocatorUpdated(address oldAllocator, address newAllocator);

    event IdleBalanceIncreased(uint256 amount, uint256 newBalance);

    event EntranceFeeSettled(uint256 assetsEquivalent, uint256 sharesMinted, address indexed recipient);

    event ExitFeeSettled(uint256 assetsEquivalent, uint256 sharesMinted, address indexed recipient);
    
    event ExitFeeWaived(bytes32 indexed requestId, uint256 grossAssets);

    event VaultDeposit(address indexed sender, address indexed receiver, uint256 assets, uint256 shares, uint256 fee);
}

src/interfaces/IPermissionManager.sol


pragma solidity ^0.8.20;

interface IPermissionManager {

    function validate(
        bytes32 action,
        address caller,
        bytes calldata params,
        bytes32[] calldata proof
    ) external view returns (bool approved);

    function grantRole(bytes32 role, address account) external;

    function revokeRole(bytes32 role, address account) external;

    function hasRole(bytes32 role, address account) external view returns (bool);

    function setMerkleRoot(bytes32 newRoot) external;

    function merkleRoot() external view returns (bytes32);

    event RoleGranted(bytes32 indexed role, address indexed account);
    event RoleRevoked(bytes32 indexed role, address indexed account);
    event MerkleRootUpdated(bytes32 oldRoot, bytes32 newRoot);
}

src/interfaces/IStrategyAdapter.sol


pragma solidity ^0.8.20;

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

interface IStrategyAdapter {

    function deposit(IERC20 asset, uint256 amount) external;

    function withdraw(IERC20 asset, uint256 amount) external;

    function totalAssets() external view returns (uint256);

    function availableLiquidity() external view returns (uint256);

    function asset() external view returns (address);

    function protocolName() external view returns (string memory);

    function leverage() external view returns (uint256);

    function healthRatio() external view returns (uint256);

    function setAllocator(address allocator) external;

    event AdapterDeposit(IERC20 indexed asset, uint256 amount);
    event AdapterWithdraw(IERC20 indexed asset, uint256 amount);
}

src/interfaces/IValuationGuard.sol


pragma solidity ^0.8.20;

interface IValuationGuard {

    function valuationBroken() external view returns (bool);
}

src/libraries/Roles.sol


pragma solidity ^0.8.20;

library Roles {
    bytes32 public constant ADMIN = keccak256("ADMIN");
    bytes32 public constant ALLOCATOR = keccak256("ALLOCATOR");
    bytes32 public constant EMERGENCY = keccak256("EMERGENCY");
    bytes32 public constant TRADER = keccak256("TRADER");
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "osaka",
  "remappings": [
    "@hyper-evm-lib/=lib/hyper-evm-lib/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "forge-std/=lib/forge-std/src/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "hyper-evm-lib/=lib/hyper-evm-lib/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.