S Price: $0.552266 (-4.91%)

Contract Diff Checker

Contract Name:
HardWorker

Contract Source Code:

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

import "@openzeppelin/contracts/utils/Strings.sol";
import "./base/Controllable.sol";
import "./libs/VaultStatusLib.sol";
import "../interfaces/IPlatform.sol";
import "../interfaces/IFactory.sol";
import "../interfaces/IVaultManager.sol";
import "../interfaces/IVault.sol";
import "../interfaces/IHardWorker.sol";
import "../integrations/gelato/IAutomate.sol";
import "../integrations/gelato/IOpsProxyFactory.sol";
import "../integrations/gelato/ITaskTreasuryUpgradable.sol";

/// @notice HardWork resolver and caller.
/// Primary executor is server script, reserve executor is Gelato Automate.
/// @author Alien Deployer (https://github.com/a17)
/// @author JodsMigel (https://github.com/JodsMigel)
contract HardWorker is Controllable, IHardWorker {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @inheritdoc IControllable
    string public constant VERSION = "1.0.0";

    address internal constant GELATO_OPS_PROXY_FACTORY = 0xC815dB16D4be6ddf2685C201937905aBf338F5D7;
    address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

    // keccak256(abi.encode(uint256(keccak256("erc7201:stability.HardWorker")) - 1)) & ~bytes32(uint256(0xff));
    bytes32 private constant HARDWORKER_STORAGE_LOCATION =
        0xb27d1d090fdefd817c9451b2e705942c4078dc680872cd693dd4ae2b2aaa9000;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STORAGE                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @custom:storage-location erc7201:stability.HardWorker
    struct HardWorkerStorage {
        mapping(address => bool) excludedVaults;
        mapping(address caller => bool allowed) dedicatedServerMsgSender;
        address dedicatedGelatoMsgSender;
        ITaskTreasuryUpgradable gelatoTaskTreasury;
        bytes32 gelatoTaskId;
        uint gelatoMinBalance;
        uint gelatoDepositAmount;
        uint delayServer;
        uint delayGelato;
        uint maxHwPerCall;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       INITIALIZATION                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    //slither-disable-next-line reentrancy-events
    function initialize(
        address platform_,
        address gelatoAutomate,
        uint gelatoMinBalance_,
        uint gelatoDepositAmount_
    ) public payable initializer {
        __Controllable_init(platform_);

        HardWorkerStorage storage $ = _getStorage();
        $.delayServer = 11 hours;
        $.delayGelato = 12 hours;

        emit Delays(11 hours, 12 hours);

        $.maxHwPerCall = 5;
        emit MaxHwPerCall(5);

        if (gelatoAutomate != address(0)) {
            // setup gelato
            $.gelatoMinBalance = gelatoMinBalance_;
            $.gelatoDepositAmount = gelatoDepositAmount_;
            //slither-disable-next-line unused-return
            (address _dedicatedGelatoMsgSender,) = IOpsProxyFactory(GELATO_OPS_PROXY_FACTORY).getProxyOf(address(this));
            $.dedicatedGelatoMsgSender = _dedicatedGelatoMsgSender;
            IAutomate automate = IAutomate(gelatoAutomate);
            ITaskTreasuryUpgradable _gelatoTaskTreasury = automate.taskTreasury();
            $.gelatoTaskTreasury = _gelatoTaskTreasury;
            emit DedicatedGelatoMsgSender(address(0), _dedicatedGelatoMsgSender);
            // create Gelato Automate task
            ModuleData memory moduleData = ModuleData({modules: new Module[](2), args: new bytes[](2)});
            moduleData.modules[0] = Module.RESOLVER;
            moduleData.modules[1] = Module.PROXY;
            moduleData.args[0] = abi.encode(address(this), abi.encodeCall(this.checkerGelato, ()));
            moduleData.args[1] = bytes("");
            bytes32 id = automate.createTask(address(this), abi.encode(this.call.selector), moduleData, address(0));
            $.gelatoTaskId = id;
            emit GelatoTask(id);
        }

        // storage location check
        // require(HARDWORKER_STORAGE_LOCATION == keccak256(abi.encode(uint256(keccak256("erc7201:stability.HardWorker")) - 1)) & ~bytes32(uint256(0xff)));
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CALLBACKS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    receive() external payable {}

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      RESTRICTED ACTIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @inheritdoc IHardWorker
    function setDedicatedServerMsgSender(address sender, bool allowed) external onlyGovernanceOrMultisig {
        HardWorkerStorage storage $ = _getStorage();
        if ($.dedicatedServerMsgSender[sender] == allowed) {
            revert AlreadyExist();
        }
        $.dedicatedServerMsgSender[sender] = allowed;
        emit DedicatedServerMsgSender(sender, allowed);
    }

    /// @inheritdoc IHardWorker
    function setDelays(uint delayServer_, uint delayGelato_) external onlyGovernanceOrMultisig {
        HardWorkerStorage storage $ = _getStorage();
        // nosemgrep
        if ($.delayServer == delayServer_ && $.delayGelato == delayGelato_) {
            revert AlreadyExist();
        }
        $.delayServer = delayServer_;
        $.delayGelato = delayGelato_;
        emit Delays(delayServer_, delayGelato_);
    }

    /// @inheritdoc IHardWorker
    //slither-disable-next-line similar-names
    function setMaxHwPerCall(uint maxHwPerCall_) external onlyOperator {
        HardWorkerStorage storage $ = _getStorage();
        if (maxHwPerCall_ <= 0) {
            revert IControllable.IncorrectZeroArgument();
        }
        $.maxHwPerCall = maxHwPerCall_;
        emit MaxHwPerCall(maxHwPerCall_);
    }

    /// @inheritdoc IHardWorker
    function changeVaultExcludeStatus(address[] memory vaults_, bool[] memory status) external onlyOperator {
        HardWorkerStorage storage $ = _getStorage();
        uint len = vaults_.length;
        if (len != status.length || len == 0) {
            revert IControllable.IncorrectArrayLength();
        }
        IFactory factory = IFactory(IPlatform(platform()).factory());
        // nosemgrep
        for (uint i; i < len; ++i) {
            // calls-loop here is not dangerous
            //slither-disable-next-line calls-loop
            if (factory.vaultStatus(vaults_[i]) == VaultStatusLib.NOT_EXIST) {
                revert NotExistWithObject(vaults_[i]);
            }
            if ($.excludedVaults[vaults_[i]] == status[i]) {
                revert AlreadyExclude(vaults_[i]);
            } else {
                $.excludedVaults[vaults_[i]] = status[i];
                emit VaultExcludeStatusChanged(vaults_[i], status[i]);
            }
        }
    }

    /// @inheritdoc IHardWorker
    //slither-disable-next-line cyclomatic-complexity
    function call(address[] memory vaults) external {
        HardWorkerStorage storage $ = _getStorage();

        uint startGas = gasleft();

        bool isServer = $.dedicatedServerMsgSender[msg.sender];
        bool isGelato = msg.sender == $.dedicatedGelatoMsgSender;
        // nosemgrep
        if (!isServer && !isGelato) {
            revert NotServerOrGelato();
        }

        if (isGelato) {
            ITaskTreasuryUpgradable _treasury = $.gelatoTaskTreasury;
            uint bal = _treasury.userTokenBalance(address(this), ETH);
            if (bal < $.gelatoMinBalance) {
                uint contractBal = address(this).balance;
                uint depositAmount = $.gelatoDepositAmount;
                if (contractBal < depositAmount) {
                    revert NotEnoughETH();
                }
                //slither-disable-next-line reentrancy-events
                _treasury.depositFunds{value: depositAmount}(address(this), ETH, 0);
                emit GelatoDeposit(depositAmount);
            }
        }

        uint _maxHwPerCall = $.maxHwPerCall;
        uint vaultsLength = vaults.length;
        uint counter;
        // nosemgrep
        for (uint i; i < vaultsLength; ++i) {
            IVault vault = IVault(vaults[i]);
            //slither-disable-next-line calls-loop
            try vault.doHardWork() {}
            catch Error(string memory _err) {
                revert(string(abi.encodePacked("Vault error: 0x", Strings.toHexString(address(vault)), " ", _err)));
            } catch (bytes memory _err) {
                revert(
                    string(
                        abi.encodePacked(
                            "Vault low-level error: 0x", Strings.toHexString(address(vault)), " ", string(_err)
                        )
                    )
                );
            }
            ++counter;
            if (counter >= _maxHwPerCall) {
                break;
            }
        }

        uint gasUsed = startGas - gasleft();
        uint gasCost = gasUsed * tx.gasprice;
        //slither-disable-start unused-return
        // nosemgrep
        if (isServer && gasCost > 0 && address(this).balance >= gasCost) {
            // nosemgrep
            //slither-disable-next-line low-level-calls
            (bool success,) = msg.sender.call{value: gasCost}("");
            if (!success) {
                revert IControllable.ETHTransferFailed();
            }
        }
        //slither-disable-end unused-return
        emit Call(counter, gasUsed, gasCost, isServer);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       VIEW FUNCTIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function getDelays() external view returns (uint delayServer, uint delayGelato) {
        HardWorkerStorage storage $ = _getStorage();
        delayServer = $.delayServer;
        delayGelato = $.delayGelato;
    }

    /// @inheritdoc IHardWorker
    function dedicatedServerMsgSender(address sender) external view returns (bool allowed) {
        return _getStorage().dedicatedServerMsgSender[sender];
    }

    /// @inheritdoc IHardWorker
    function dedicatedGelatoMsgSender() external view returns (address) {
        return _getStorage().dedicatedGelatoMsgSender;
    }

    /// @inheritdoc IHardWorker
    function gelatoMinBalance() external view returns (uint) {
        return _getStorage().gelatoMinBalance;
    }

    /// @inheritdoc IHardWorker
    function maxHwPerCall() external view returns (uint) {
        return _getStorage().maxHwPerCall;
    }

    /// @inheritdoc IHardWorker
    function checkerServer() external view returns (bool canExec, bytes memory execPayload) {
        return _checker(_getStorage().delayServer);
    }

    /// @inheritdoc IHardWorker
    function checkerGelato() external view returns (bool canExec, bytes memory execPayload) {
        return _checker(_getStorage().delayGelato);
    }

    /// @inheritdoc IHardWorker
    function gelatoBalance() external view returns (uint) {
        return _getStorage().gelatoTaskTreasury.userTokenBalance(address(this), ETH);
    }

    /// @inheritdoc IHardWorker
    function excludedVaults(address vault) external view returns (bool) {
        return _getStorage().excludedVaults[vault];
    }

    /// @inheritdoc IHardWorker
    function gelatoTaskId() external view returns (bytes32) {
        return _getStorage().gelatoTaskId;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       INTERNAL LOGIC                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function _getStorage() private pure returns (HardWorkerStorage storage $) {
        //slither-disable-next-line assembly
        assembly {
            $.slot := HARDWORKER_STORAGE_LOCATION
        }
    }

    function _checker(uint delay_) internal view returns (bool canExec, bytes memory execPayload) {
        HardWorkerStorage storage $ = _getStorage();
        IPlatform _platform = IPlatform(platform());
        IFactory factory = IFactory(_platform.factory());
        address[] memory vaults = IVaultManager(_platform.vaultManager()).vaultAddresses();
        uint len = vaults.length;
        address[] memory vaultsForHardWork = new address[](len);
        //slither-disable-next-line uninitialized-local
        uint counter;
        // nosemgrep
        for (uint i; i < len; ++i) {
            if ($.excludedVaults[vaults[i]]) {
                continue;
            }

            IVault vault = IVault(vaults[i]);
            IStrategy strategy = vault.strategy();
            //slither-disable-next-line unused-return
            (uint tvl,) = vault.tvl();
            // nosemgrep
            if (
                //slither-disable-next-line timestamp
                tvl > 0 && block.timestamp - strategy.lastHardWork() > delay_
                    && factory.vaultStatus(vaults[i]) == VaultStatusLib.ACTIVE
            ) {
                ++counter;
                vaultsForHardWork[i] = vaults[i];
            }
        }

        if (counter == 0) {
            return (false, bytes("No ready vaults"));
        } else {
            address[] memory vaultsResult = new address[](counter);
            uint j;
            // nosemgrep
            for (uint i; i < len; ++i) {
                if (vaultsForHardWork[i] == address(0)) {
                    continue;
                }

                vaultsResult[j] = vaultsForHardWork[i];
                ++j;
            }

            return (true, abi.encodeWithSelector(HardWorker.call.selector, vaultsResult));
        }
    }
}

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

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

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

import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "../libs/SlotsLib.sol";
import "../../interfaces/IControllable.sol";
import "../../interfaces/IPlatform.sol";

/// @dev Base core contract.
///      It store an immutable platform proxy address in the storage and provides access control to inherited contracts.
/// @author Alien Deployer (https://github.com/a17)
/// @author 0xhokugava (https://github.com/0xhokugava)
abstract contract Controllable is Initializable, IControllable, ERC165 {
    using SlotsLib for bytes32;

    string public constant CONTROLLABLE_VERSION = "1.0.0";
    bytes32 internal constant _PLATFORM_SLOT = bytes32(uint(keccak256("eip1967.controllable.platform")) - 1);
    bytes32 internal constant _CREATED_BLOCK_SLOT = bytes32(uint(keccak256("eip1967.controllable.created_block")) - 1);

    /// @dev Prevent implementation init
    constructor() {
        _disableInitializers();
    }

    /// @notice Initialize contract after setup it as proxy implementation
    ///         Save block.timestamp in the "created" variable
    /// @dev Use it only once after first logic setup
    /// @param platform_ Platform address
    //slither-disable-next-line naming-convention
    function __Controllable_init(address platform_) internal onlyInitializing {
        if (platform_ == address(0) || IPlatform(platform_).multisig() == address(0)) {
            revert IncorrectZeroArgument();
        }
        SlotsLib.set(_PLATFORM_SLOT, platform_); // syntax for forge coverage
        _CREATED_BLOCK_SLOT.set(block.number);
        emit ContractInitialized(platform_, block.timestamp, block.number);
    }

    modifier onlyGovernance() {
        _requireGovernance();
        _;
    }

    modifier onlyMultisig() {
        _requireMultisig();
        _;
    }

    modifier onlyGovernanceOrMultisig() {
        _requireGovernanceOrMultisig();
        _;
    }

    modifier onlyOperator() {
        _requireOperator();
        _;
    }

    modifier onlyFactory() {
        _requireFactory();
        _;
    }

    // ************* SETTERS/GETTERS *******************

    /// @inheritdoc IControllable
    function platform() public view override returns (address) {
        return _PLATFORM_SLOT.getAddress();
    }

    /// @inheritdoc IControllable
    function createdBlock() external view override returns (uint) {
        return _CREATED_BLOCK_SLOT.getUint();
    }

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IControllable).interfaceId || super.supportsInterface(interfaceId);
    }

    function _requireGovernance() internal view {
        if (IPlatform(platform()).governance() != msg.sender) {
            revert NotGovernance();
        }
    }

    function _requireMultisig() internal view {
        if (!IPlatform(platform()).isOperator(msg.sender)) {
            revert NotMultisig();
        }
    }

    function _requireGovernanceOrMultisig() internal view {
        IPlatform _platform = IPlatform(platform());
        // nosemgrep
        if (_platform.governance() != msg.sender && _platform.multisig() != msg.sender) {
            revert NotGovernanceAndNotMultisig();
        }
    }

    function _requireOperator() internal view {
        if (!IPlatform(platform()).isOperator(msg.sender)) {
            revert NotOperator();
        }
    }

    function _requireFactory() internal view {
        if (IPlatform(platform()).factory() != msg.sender) {
            revert NotFactory();
        }
    }
}

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

library VaultStatusLib {
    uint internal constant NOT_EXIST = 0;
    uint internal constant ACTIVE = 1;
    uint internal constant DEPRECATED = 2;
    uint internal constant EMERGENCY_EXIT = 3;
    uint internal constant DISABLED = 4;
    uint internal constant DEPOSITS_UNAVAILABLE = 5;
}

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

/// @notice Interface of the main contract and entry point to the platform.
/// @author Alien Deployer (https://github.com/a17)
/// @author Jude (https://github.com/iammrjude)
/// @author JodsMigel (https://github.com/JodsMigel)
interface IPlatform {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    error AlreadyAnnounced();
    error SameVersion();
    error NoNewVersion();
    error UpgradeTimerIsNotOver(uint TimerTimestamp);
    error IncorrectFee(uint minFee, uint maxFee);
    error NotEnoughAllowedBBToken();
    error TokenAlreadyExistsInSet(address token);
    error AggregatorNotExists(address dexAggRouter);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           EVENTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    event PlatformVersion(string version);
    event UpgradeAnnounce(
        string oldVersion, string newVersion, address[] proxies, address[] newImplementations, uint timelock
    );
    event CancelUpgrade(string oldVersion, string newVersion);
    event ProxyUpgraded(
        address indexed proxy, address implementation, string oldContractVersion, string newContractVersion
    );
    event Addresses(
        address multisig_,
        address factory_,
        address priceReader_,
        address swapper_,
        address buildingPermitToken_,
        address vaultManager_,
        address strategyLogic_,
        address aprOracle_,
        address hardWorker,
        address rebalancer,
        address zap,
        address bridge
    );
    event OperatorAdded(address operator);
    event OperatorRemoved(address operator);
    event FeesChanged(uint fee, uint feeShareVaultManager, uint feeShareStrategyLogic, uint feeShareEcosystem);
    event MinInitialBoostChanged(uint minInitialBoostPerDay, uint minInitialBoostDuration);
    event NewAmmAdapter(string id, address proxy);
    event EcosystemRevenueReceiver(address receiver);
    event SetAllowedBBTokenVaults(address bbToken, uint vaultsToBuild, bool firstSet);
    event RemoveAllowedBBToken(address bbToken);
    event AddAllowedBoostRewardToken(address token);
    event RemoveAllowedBoostRewardToken(address token);
    event AddDefaultBoostRewardToken(address token);
    event RemoveDefaultBoostRewardToken(address token);
    event AddBoostTokens(address[] allowedBoostRewardToken, address[] defaultBoostRewardToken);
    event AllowedBBTokenVaultUsed(address bbToken, uint vaultToUse);
    event AddDexAggregator(address router);
    event RemoveDexAggregator(address router);
    event MinTvlForFreeHardWorkChanged(uint oldValue, uint newValue);
    event CustomVaultFee(address vault, uint platformFee);
    event Rebalancer(address rebalancer_);
    event Bridge(address bridge_);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         DATA TYPES                         */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    struct PlatformUpgrade {
        string newVersion;
        address[] proxies;
        address[] newImplementations;
    }

    struct PlatformSettings {
        string networkName;
        bytes32 networkExtra;
        uint fee;
        uint feeShareVaultManager;
        uint feeShareStrategyLogic;
        uint feeShareEcosystem;
        uint minInitialBoostPerDay;
        uint minInitialBoostDuration;
    }

    struct AmmAdapter {
        string id;
        address proxy;
    }

    struct SetupAddresses {
        address factory;
        address priceReader;
        address swapper;
        address buildingPermitToken;
        address buildingPayPerVaultToken;
        address vaultManager;
        address strategyLogic;
        address aprOracle;
        address targetExchangeAsset;
        address hardWorker;
        address zap;
        address bridge;
        address rebalancer;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      VIEW FUNCTIONS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @notice Platform version in CalVer scheme: YY.MM.MINOR-tag. Updates on core contract upgrades.
    function platformVersion() external view returns (string memory);

    /// @notice Time delay for proxy upgrades of core contracts and changing important platform settings by multisig
    //slither-disable-next-line naming-convention
    function TIME_LOCK() external view returns (uint);

    /// @notice DAO governance
    function governance() external view returns (address);

    /// @notice Core team multi signature wallet. Development and operations fund
    function multisig() external view returns (address);

    /// @notice This NFT allow user to build limited number of vaults per week
    function buildingPermitToken() external view returns (address);

    /// @notice This ERC20 token is used as payment token for vault building
    function buildingPayPerVaultToken() external view returns (address);

    /// @notice Receiver of ecosystem revenue
    function ecosystemRevenueReceiver() external view returns (address);

    /// @dev The best asset in a network for swaps between strategy assets and farms rewards assets
    ///      The target exchange asset is used for finding the best strategy's exchange asset.
    ///      Rhe fewer routes needed to swap to the target exchange asset, the better.
    function targetExchangeAsset() external view returns (address);

    /// @notice Platform factory assembling vaults. Stores settings, strategy logic, farms.
    /// Provides the opportunity to upgrade vaults and strategies.
    /// @return Address of Factory proxy
    function factory() external view returns (address);

    /// @notice The holders of these NFT receive a share of the vault revenue
    /// @return Address of VaultManager proxy
    function vaultManager() external view returns (address);

    /// @notice The holders of these tokens receive a share of the revenue received in all vaults using this strategy logic.
    function strategyLogic() external view returns (address);

    /// @notice Combining oracle and DeX spot prices
    /// @return Address of PriceReader proxy
    function priceReader() external view returns (address);

    /// @notice Providing underlying assets APRs on-chain
    /// @return Address of AprOracle proxy
    function aprOracle() external view returns (address);

    /// @notice On-chain price quoter and swapper
    /// @return Address of Swapper proxy
    function swapper() external view returns (address);

    /// @notice HardWork resolver and caller
    /// @return Address of HardWorker proxy
    function hardWorker() external view returns (address);

    /// @notice Rebalance resolver
    /// @return Address of Rebalancer proxy
    function rebalancer() external view returns (address);

    /// @notice ZAP feature
    /// @return Address of Zap proxy
    function zap() external view returns (address);

    /// @notice Stability Bridge
    /// @return Address of Bridge proxy
    function bridge() external view returns (address);

    /// @notice Name of current EVM network
    function networkName() external view returns (string memory);

    /// @notice Minimal initial boost rewards per day USD amount which needs to create rewarding vault
    function minInitialBoostPerDay() external view returns (uint);

    /// @notice Minimal boost rewards vesting duration for initial boost
    function minInitialBoostDuration() external view returns (uint);

    /// @notice This function provides the timestamp of the platform upgrade timelock.
    /// @dev This function is an external view function, meaning it doesn't modify the state.
    /// @return uint representing the timestamp of the platform upgrade timelock.
    function platformUpgradeTimelock() external view returns (uint);

    /// @dev Extra network data
    /// @return 0-2 bytes - color
    ///         3-5 bytes - background color
    ///         6-31 bytes - free
    function networkExtra() external view returns (bytes32);

    /// @notice Pending platform upgrade data
    function pendingPlatformUpgrade() external view returns (PlatformUpgrade memory);

    /// @notice Get platform revenue fee settings
    /// @return fee Revenue fee % (between MIN_FEE - MAX_FEE) with DENOMINATOR precision.
    /// @return feeShareVaultManager Revenue fee share % of VaultManager tokenId owner
    /// @return feeShareStrategyLogic Revenue fee share % of StrategyLogic tokenId owner
    /// @return feeShareEcosystem Revenue fee share % of ecosystemFeeReceiver
    function getFees()
        external
        view
        returns (uint fee, uint feeShareVaultManager, uint feeShareStrategyLogic, uint feeShareEcosystem);

    /// @notice Get custom vault platform fee
    /// @return fee revenue fee % with DENOMINATOR precision
    function getCustomVaultFee(address vault) external view returns (uint fee);

    /// @notice Platform settings
    function getPlatformSettings() external view returns (PlatformSettings memory);

    /// @notice AMM adapters of the platform
    function getAmmAdapters() external view returns (string[] memory id, address[] memory proxy);

    /// @notice Get AMM adapter data by hash
    /// @param ammAdapterIdHash Keccak256 hash of adapter ID string
    /// @return ID string and proxy address of AMM adapter
    function ammAdapter(bytes32 ammAdapterIdHash) external view returns (AmmAdapter memory);

    /// @notice Allowed buy-back tokens for rewarding vaults
    function allowedBBTokens() external view returns (address[] memory);

    /// @notice Vaults building limit for buy-back token.
    /// This limit decrements when a vault for BB-token is built.
    /// @param token Allowed buy-back token
    /// @return vaultsLimit Number of vaults that can be built for BB-token
    function allowedBBTokenVaults(address token) external view returns (uint vaultsLimit);

    /// @notice Vaults building limits for allowed buy-back tokens.
    /// @return bbToken Allowed buy-back tokens
    /// @return vaultsLimit Number of vaults that can be built for BB-tokens
    function allowedBBTokenVaults() external view returns (address[] memory bbToken, uint[] memory vaultsLimit);

    /// @notice Non-zero vaults building limits for allowed buy-back tokens.
    /// @return bbToken Allowed buy-back tokens
    /// @return vaultsLimit Number of vaults that can be built for BB-tokens
    function allowedBBTokenVaultsFiltered()
        external
        view
        returns (address[] memory bbToken, uint[] memory vaultsLimit);

    /// @notice Check address for existance in operators list
    /// @param operator Address
    /// @return True if this address is Stability Operator
    function isOperator(address operator) external view returns (bool);

    /// @notice Tokens that can be used for boost rewards of rewarding vaults
    /// @return Addresses of tokens
    function allowedBoostRewardTokens() external view returns (address[] memory);

    /// @notice Allowed boost reward tokens that used for unmanaged rewarding vaults creation
    /// @return Addresses of tokens
    function defaultBoostRewardTokens() external view returns (address[] memory);

    /// @notice Allowed boost reward tokens that used for unmanaged rewarding vaults creation
    /// @param addressToRemove This address will be removed from default boost reward tokens
    /// @return Addresses of tokens
    function defaultBoostRewardTokensFiltered(address addressToRemove) external view returns (address[] memory);

    /// @notice Allowed DeX aggregators
    /// @return Addresses of DeX aggregator rounters
    function dexAggregators() external view returns (address[] memory);

    /// @notice DeX aggregator router address is allowed to be used in the platform
    /// @param dexAggRouter Address of DeX aggreagator router
    /// @return Can be used
    function isAllowedDexAggregatorRouter(address dexAggRouter) external view returns (bool);

    /// @notice Show minimum TVL for compensate if vault has not enough ETH
    /// @return Minimum TVL for compensate.
    function minTvlForFreeHardWork() external view returns (uint);

    /// @notice Front-end platform viewer
    /// @return platformAddresses Platform core addresses
    ///        platformAddresses[0] factory
    ///        platformAddresses[1] vaultManager
    ///        platformAddresses[2] strategyLogic
    ///        platformAddresses[3] buildingPermitToken
    ///        platformAddresses[4] buildingPayPerVaultToken
    ///        platformAddresses[5] governance
    ///        platformAddresses[6] multisig
    ///        platformAddresses[7] zap
    ///        platformAddresses[8] bridge
    /// @return bcAssets Blue chip token addresses
    /// @return dexAggregators_ DeX aggregators allowed to be used entire the platform
    /// @return vaultType Vault type ID strings
    /// @return vaultExtra Vault color, background color and other extra data. Index of vault same as in previous array.
    /// @return vaultBulldingPrice Price of creating new vault in buildingPayPerVaultToken. Index of vault same as in previous array.
    /// @return strategyId Strategy logic ID strings
    /// @return isFarmingStrategy True if strategy is farming strategy. Index of strategy same as in previous array.
    /// @return strategyTokenURI StrategyLogic NFT tokenId metadata and on-chain image. Index of strategy same as in previous array.
    /// @return strategyExtra Strategy color, background color and other extra data. Index of strategy same as in previous array.
    function getData()
        external
        view
        returns (
            address[] memory platformAddresses,
            address[] memory bcAssets,
            address[] memory dexAggregators_,
            string[] memory vaultType,
            bytes32[] memory vaultExtra,
            uint[] memory vaultBulldingPrice,
            string[] memory strategyId,
            bool[] memory isFarmingStrategy,
            string[] memory strategyTokenURI,
            bytes32[] memory strategyExtra
        );

    // todo add vaultSymbol, vaultName
    /// @notice Front-end balances, prices and vault list viewer
    /// @param yourAccount Address of account to query balances
    /// @return token Tokens supported by the platform
    /// @return tokenPrice USD price of token. Index of token same as in previous array.
    /// @return tokenUserBalance User balance of token. Index of token same as in previous array.
    /// @return vault Deployed vaults
    /// @return vaultSharePrice Price 1.0 vault share. Index of vault same as in previous array.
    /// @return vaultUserBalance User balance of vault. Index of vault same as in previous array.
    /// @return nft Ecosystem NFTs
    ///         nft[0] BuildingPermitToken
    ///         nft[1] VaultManager
    ///         nft[2] StrategyLogic
    /// @return nftUserBalance User balance of NFT. Index of NFT same as in previous array.
    /// @return buildingPayPerVaultTokenBalance User balance of vault creation paying token
    function getBalance(address yourAccount)
        external
        view
        returns (
            address[] memory token,
            uint[] memory tokenPrice,
            uint[] memory tokenUserBalance,
            address[] memory vault,
            uint[] memory vaultSharePrice,
            uint[] memory vaultUserBalance,
            address[] memory nft,
            uint[] memory nftUserBalance,
            uint buildingPayPerVaultTokenBalance
        );

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      WRITE FUNCTIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @notice Add platform operator.
    /// Only governance and multisig can add operator.
    /// @param operator Address of new operator
    function addOperator(address operator) external;

    /// @notice Remove platform operator.
    /// Only governance and multisig can remove operator.
    /// @param operator Address of operator to remove
    function removeOperator(address operator) external;

    /// @notice Announce upgrade of platform proxies implementations
    /// Only governance and multisig can announce platform upgrades.
    /// @param newVersion New platform version. Version must be changed when upgrading.
    /// @param proxies Addresses of core contract proxies
    /// @param newImplementations New implementation for proxy. Index of proxy same as in previous array.
    function announcePlatformUpgrade(
        string memory newVersion,
        address[] memory proxies,
        address[] memory newImplementations
    ) external;

    /// @notice Upgrade platform
    /// Only operator (multisig is operator too) can ececute pending platform upgrade
    function upgrade() external;

    /// @notice Cancel pending platform upgrade
    /// Only operator (multisig is operator too) can ececute pending platform upgrade
    function cancelUpgrade() external;

    /// @notice Register AMM adapter in platform
    /// @param id AMM adapter ID string from AmmAdapterIdLib
    /// @param proxy Address of AMM adapter proxy
    function addAmmAdapter(string memory id, address proxy) external;

    // todo Only governance and multisig can set allowed bb-token vaults building limit
    /// @notice Set new vaults building limit for buy-back token
    /// @param bbToken Address of allowed buy-back token
    /// @param vaultsToBuild Number of vaults that can be built for BB-token
    function setAllowedBBTokenVaults(address bbToken, uint vaultsToBuild) external;

    // todo Only governance and multisig can add allowed boost reward token
    /// @notice Add new allowed boost reward token
    /// @param token Address of token
    function addAllowedBoostRewardToken(address token) external;

    // todo Only governance and multisig can remove allowed boost reward token
    /// @notice Remove allowed boost reward token
    /// @param token Address of allowed boost reward token
    function removeAllowedBoostRewardToken(address token) external;

    // todo Only governance and multisig can add default boost reward token
    /// @notice Add default boost reward token
    /// @param token Address of default boost reward token
    function addDefaultBoostRewardToken(address token) external;

    // todo Only governance and multisig can remove default boost reward token
    /// @notice Remove default boost reward token
    /// @param token Address of allowed boost reward token
    function removeDefaultBoostRewardToken(address token) external;

    // todo Only governance and multisig can add allowed boost reward token
    // todo Only governance and multisig can add default boost reward token
    /// @notice Add new allowed boost reward token
    /// @notice Add default boost reward token
    /// @param allowedBoostRewardToken Address of allowed boost reward token
    /// @param defaultBoostRewardToken Address of default boost reward token
    function addBoostTokens(
        address[] memory allowedBoostRewardToken,
        address[] memory defaultBoostRewardToken
    ) external;

    /// @notice Decrease allowed BB-token vault building limit when vault is built
    /// Only Factory can do it.
    /// @param bbToken Address of allowed buy-back token
    function useAllowedBBTokenVault(address bbToken) external;

    /// @notice Allow DeX aggregator routers to be used in the platform
    /// @param dexAggRouter Addresses of DeX aggreagator routers
    function addDexAggregators(address[] memory dexAggRouter) external;

    /// @notice Remove allowed DeX aggregator router from the platform
    /// @param dexAggRouter Address of DeX aggreagator router
    function removeDexAggregator(address dexAggRouter) external;

    /// @notice Change initial boost rewards settings
    /// @param minInitialBoostPerDay_ Minimal initial boost rewards per day USD amount which needs to create rewarding vault
    /// @param minInitialBoostDuration_ Minimal boost rewards vesting duration for initial boost
    function setInitialBoost(uint minInitialBoostPerDay_, uint minInitialBoostDuration_) external;

    /// @notice Update new minimum TVL for compensate.
    /// @param value New minimum TVL for compensate.
    function setMinTvlForFreeHardWork(uint value) external;

    /// @notice Set custom platform fee for vault
    /// @param vault Vault address
    /// @param platformFee Custom platform fee
    function setCustomVaultFee(address vault, uint platformFee) external;

    /// @notice Setup Rebalancer.
    /// Only Goverannce or Multisig can do this when Rebalancer is not set.
    /// @param rebalancer_ Proxy address of Bridge
    function setupRebalancer(address rebalancer_) external;

    /// @notice Setup Bridge.
    /// Only Goverannce or Multisig can do this when Bridge is not set.
    /// @param bridge_ Proxy address of Bridge
    function setupBridge(address bridge_) external;
}

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

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

/// @notice Creating vaults, upgrading vaults and strategies, vault list, farms and strategy logics management
/// @author Alien Deployer (https://github.com/a17)
/// @author Jude (https://github.com/iammrjude)
/// @author JodsMigel (https://github.com/JodsMigel)
/// @author HCrypto7 (https://github.com/hcrypto7)
interface IFactory {
    //region ----- Custom Errors -----

    error VaultImplementationIsNotAvailable();
    error VaultNotAllowedToDeploy();
    error StrategyImplementationIsNotAvailable();
    error StrategyLogicNotAllowedToDeploy();
    error YouDontHaveEnoughTokens(uint userBalance, uint requireBalance, address payToken);
    error SuchVaultAlreadyDeployed(bytes32 key);
    error NotActiveVault();
    error UpgradeDenied(bytes32 _hash);
    error AlreadyLastVersion(bytes32 _hash);
    error NotStrategy();
    error BoostDurationTooLow();
    error BoostAmountTooLow();
    error BoostAmountIsZero();

    //endregion ----- Custom Errors -----

    //region ----- Events -----

    event VaultAndStrategy(
        address indexed deployer,
        string vaultType,
        string strategyId,
        address vault,
        address strategy,
        string name,
        string symbol,
        address[] assets,
        bytes32 deploymentKey,
        uint vaultManagerTokenId
    );
    event StrategyProxyUpgraded(address proxy, address oldImplementation, address newImplementation);
    event VaultProxyUpgraded(address proxy, address oldImplementation, address newImplementation);
    event VaultConfigChanged(
        string type_, address implementation, bool deployAllowed, bool upgradeAllowed, bool newVaultType
    );
    event StrategyLogicConfigChanged(
        string id, address implementation, bool deployAllowed, bool upgradeAllowed, bool newStrategy
    );
    event VaultStatus(address indexed vault, uint newStatus);
    event NewFarm(Farm[] farms);
    event UpdateFarm(uint id, Farm farm);
    event SetStrategyAvailableInitParams(string id, address[] initAddresses, uint[] initNums, int24[] initTicks);
    event AliasNameChanged(address indexed operator, address indexed tokenAddress, string newAliasName);

    //endregion -- Events -----

    //region ----- Data types -----

    /// @custom:storage-location erc7201:stability.Factory
    struct FactoryStorage {
        /// @inheritdoc IFactory
        mapping(bytes32 typeHash => VaultConfig) vaultConfig;
        /// @inheritdoc IFactory
        mapping(bytes32 idHash => StrategyLogicConfig) strategyLogicConfig;
        /// @inheritdoc IFactory
        mapping(bytes32 deploymentKey => address vaultProxy) deploymentKey;
        /// @inheritdoc IFactory
        mapping(address vault => uint status) vaultStatus;
        /// @inheritdoc IFactory
        mapping(address address_ => bool isStrategy_) isStrategy;
        EnumerableSet.Bytes32Set vaultTypeHashes;
        EnumerableSet.Bytes32Set strategyLogicIdHashes;
        mapping(uint week => mapping(uint builderPermitTokenId => uint vaultsBuilt)) vaultsBuiltByPermitTokenId;
        address[] deployedVaults;
        Farm[] farms;
        /// @inheritdoc IFactory
        mapping(bytes32 idHash => StrategyAvailableInitParams) strategyAvailableInitParams;
        mapping(address tokenAddress => string aliasName) aliasNames;
    }

    struct VaultConfig {
        string vaultType;
        address implementation;
        bool deployAllowed;
        bool upgradeAllowed;
        uint buildingPrice;
    }

    struct StrategyLogicConfig {
        string id;
        address implementation;
        bool deployAllowed;
        bool upgradeAllowed;
        bool farming;
        uint tokenId;
    }

    struct Farm {
        uint status;
        address pool;
        string strategyLogicId;
        address[] rewardAssets;
        address[] addresses;
        uint[] nums;
        int24[] ticks;
    }

    struct StrategyAvailableInitParams {
        address[] initAddresses;
        uint[] initNums;
        int24[] initTicks;
    }

    //endregion -- Data types -----

    //region ----- View functions -----

    /// @notice All vaults deployed by the factory
    /// @return Vault proxy addresses
    function deployedVaults() external view returns (address[] memory);

    /// @notice Total vaults deployed
    function deployedVaultsLength() external view returns (uint);

    /// @notice Get vault by VaultManager tokenId
    /// @param id Vault array index. Same as tokenId of VaultManager NFT
    /// @return Address of VaultProxy
    function deployedVault(uint id) external view returns (address);

    /// @notice All farms known by the factory in current network
    function farms() external view returns (Farm[] memory);

    /// @notice Total farms known by the factory in current network
    function farmsLength() external view returns (uint);

    /// @notice Farm data by farm index
    /// @param id Index of farm
    function farm(uint id) external view returns (Farm memory);

    /// @notice Strategy logic settings
    /// @param idHash keccak256 hash of strategy logic string ID
    /// @return config Strategy logic settings
    function strategyLogicConfig(bytes32 idHash) external view returns (StrategyLogicConfig memory config);

    /// @notice All known strategies
    /// @return Array of keccak256 hashes of strategy logic string ID
    function strategyLogicIdHashes() external view returns (bytes32[] memory);

    // todo remove, use new function without calculating vault symbol on the fly for not initialized vaults
    // factory required that special functionally only internally, not for interface
    function getStrategyData(
        string memory vaultType,
        address strategyAddress,
        address bbAsset
    )
        external
        view
        returns (
            string memory strategyId,
            address[] memory assets,
            string[] memory assetsSymbols,
            string memory specificName,
            string memory vaultSymbol
        );

    /// @dev Get best asset of assets to be strategy exchange asset
    function getExchangeAssetIndex(address[] memory assets) external view returns (uint);

    /// @notice Deployment key of created vault
    /// @param deploymentKey_ Hash of concatenated unique vault and strategy initialization parameters
    /// @return Address of deployed vault
    function deploymentKey(bytes32 deploymentKey_) external view returns (address);

    /// @notice Calculating deployment key based on unique vault and strategy initialization parameters
    /// @param vaultType Vault type string
    /// @param strategyId Strategy logic Id string
    /// @param vaultInitAddresses Vault initizlization addresses for deployVaultAndStrategy method
    /// @param vaultInitNums Vault initizlization uint numbers for deployVaultAndStrategy method
    /// @param strategyInitAddresses Strategy initizlization addresses for deployVaultAndStrategy method
    /// @param strategyInitNums Strategy initizlization uint numbers for deployVaultAndStrategy method
    /// @param strategyInitTicks Strategy initizlization int24 ticks for deployVaultAndStrategy method
    function getDeploymentKey(
        string memory vaultType,
        string memory strategyId,
        address[] memory vaultInitAddresses,
        uint[] memory vaultInitNums,
        address[] memory strategyInitAddresses,
        uint[] memory strategyInitNums,
        int24[] memory strategyInitTicks
    ) external returns (bytes32);

    /// @notice Available variants of new vault for creating.
    /// The structure of the function's output values is complex,
    /// but after parsing them, the front end has all the data to generate a list of vaults to create.
    /// @return desc Descriptions of the strategy for making money
    /// @return vaultType Vault type strings. Output values are matched by index with previous array.
    /// @return strategyId Strategy logic ID strings. Output values are matched by index with previous array.
    /// @return initIndexes Map of start and end indexes in next 5 arrays. Output values are matched by index with previous array.
    ///                 [0] Start index in vaultInitAddresses
    ///                 [1] End index in vaultInitAddresses
    ///                 [2] Start index in vaultInitNums
    ///                 [3] End index in vaultInitNums
    ///                 [4] Start index in strategyInitAddresses
    ///                 [5] End index in strategyInitAddresses
    ///                 [6] Start index in strategyInitNums
    ///                 [7] End index in strategyInitNums
    ///                 [8] Start index in strategyInitTicks
    ///                 [9] End index in strategyInitTicks
    /// @return vaultInitAddresses Vault initizlization addresses for deployVaultAndStrategy method for all building variants.
    /// @return vaultInitNums Vault initizlization uint numbers for deployVaultAndStrategy method for all building variants.
    /// @return strategyInitAddresses Strategy initizlization addresses for deployVaultAndStrategy method for all building variants.
    /// @return strategyInitNums Strategy initizlization uint numbers for deployVaultAndStrategy method for all building variants.
    /// @return strategyInitTicks Strategy initizlization int24 ticks for deployVaultAndStrategy method for all building variants.
    function whatToBuild()
        external
        view
        returns (
            string[] memory desc,
            string[] memory vaultType,
            string[] memory strategyId,
            uint[10][] memory initIndexes,
            address[] memory vaultInitAddresses,
            uint[] memory vaultInitNums,
            address[] memory strategyInitAddresses,
            uint[] memory strategyInitNums,
            int24[] memory strategyInitTicks
        );

    /// @notice Governance and multisig can set a vault status other than Active - the default status.
    /// HardWorker only works with active vaults.
    /// @return status Constant from VaultStatusLib
    function vaultStatus(address vault) external view returns (uint status);

    /// @notice Check that strategy proxy deployed by the Factory
    /// @param address_ Address of contract
    /// @return This address is our strategy proxy
    function isStrategy(address address_) external view returns (bool);

    /// @notice How much vaults was built by builderPermitToken NFT tokenId in week
    /// @param week Week index (timestamp / (86400 * 7))
    /// @param builderPermitTokenId Token ID of buildingPermitToken NFT
    /// @return vaultsBuilt Vaults built
    function vaultsBuiltByPermitTokenId(
        uint week,
        uint builderPermitTokenId
    ) external view returns (uint vaultsBuilt);

    /// @notice Data on all factory strategies.
    /// The output values are matched by index in the arrays.
    /// @return id Strategy logic ID strings
    /// @return deployAllowed New vaults can be deployed
    /// @return upgradeAllowed Strategy can be upgraded
    /// @return farming It is farming strategy (earns farming/gauge rewards)
    /// @return tokenId Token ID of StrategyLogic NFT
    /// @return tokenURI StrategyLogic NFT tokenId metadata and on-chain image
    /// @return extra Strategy color, background color and other extra data
    function strategies()
        external
        view
        returns (
            string[] memory id,
            bool[] memory deployAllowed,
            bool[] memory upgradeAllowed,
            bool[] memory farming,
            uint[] memory tokenId,
            string[] memory tokenURI,
            bytes32[] memory extra
        );

    /// @notice Get config of vault type
    /// @param typeHash Keccak256 hash of vault type string
    /// @return vaultType Vault type string
    /// @return implementation Vault implementation address
    /// @return deployAllowed New vaults can be deployed
    /// @return upgradeAllowed Vaults can be upgraded
    /// @return buildingPrice Price of building new vault
    function vaultConfig(bytes32 typeHash)
        external
        view
        returns (
            string memory vaultType,
            address implementation,
            bool deployAllowed,
            bool upgradeAllowed,
            uint buildingPrice
        );

    /// @notice Data on all factory vault types
    /// The output values are matched by index in the arrays.
    /// @return vaultType Vault type string
    /// @return implementation Address of vault implemented logic
    /// @return deployAllowed New vaults can be deployed
    /// @return upgradeAllowed Vaults can be upgraded
    /// @return buildingPrice  Price of building new vault
    /// @return extra Vault type color, background color and other extra data
    function vaultTypes()
        external
        view
        returns (
            string[] memory vaultType,
            address[] memory implementation,
            bool[] memory deployAllowed,
            bool[] memory upgradeAllowed,
            uint[] memory buildingPrice,
            bytes32[] memory extra
        );

    /// @notice Initialization strategy params store
    function strategyAvailableInitParams(bytes32 idHash) external view returns (StrategyAvailableInitParams memory);

    /// @notice Retrieves the alias name associated with a given address
    /// @param tokenAddress_ The address to query for its alias name
    /// @return The alias name associated with the provided address
    function getAliasName(address tokenAddress_) external view returns (string memory);

    //endregion -- View functions -----

    //region ----- Write functions -----

    /// @notice Main method of the Factory - new vault creation by user.
    /// @param vaultType Vault type ID string
    /// @param strategyId Strategy logic ID string
    /// Different types of vaults and strategies have different lengths of input arrays.
    /// @param vaultInitAddresses Addresses for vault initialization
    /// @param vaultInitNums Numbers for vault initialization
    /// @param strategyInitAddresses Addresses for strategy initialization
    /// @param strategyInitNums Numbers for strategy initialization
    /// @param strategyInitTicks Ticks for strategy initialization
    /// @return vault Deployed VaultProxy address
    /// @return strategy Deployed StrategyProxy address
    function deployVaultAndStrategy(
        string memory vaultType,
        string memory strategyId,
        address[] memory vaultInitAddresses,
        uint[] memory vaultInitNums,
        address[] memory strategyInitAddresses,
        uint[] memory strategyInitNums,
        int24[] memory strategyInitTicks
    ) external returns (address vault, address strategy);

    /// @notice Upgrade vault proxy. Can be called by any address.
    /// @param vault Address of vault proxy for upgrade
    function upgradeVaultProxy(address vault) external;

    /// @notice Upgrade strategy proxy. Can be called by any address.
    /// @param strategy Address of strategy proxy for upgrade
    function upgradeStrategyProxy(address strategy) external;

    /// @notice Add farm to factory
    /// @param farms_ Settings and data required to work with the farm.
    function addFarms(Farm[] memory farms_) external;

    /// @notice Update farm
    /// @param id Farm index
    /// @param farm_ Settings and data required to work with the farm.
    function updateFarm(uint id, Farm memory farm_) external;

    /// @notice Initial addition or change of vault type settings.
    /// Operator can add new vault type. Governance or multisig can change existing vault type config.
    /// @param vaultConfig_ Vault type settings
    function setVaultConfig(VaultConfig memory vaultConfig_) external;

    /// @notice Initial addition or change of strategy logic settings.
    /// Operator can add new strategy logic. Governance or multisig can change existing logic config.
    /// @param config Strategy logic settings
    /// @param developer Strategy developer is receiver of minted StrategyLogic NFT on initial addition
    function setStrategyLogicConfig(StrategyLogicConfig memory config, address developer) external;

    /// @notice Governance and multisig can set a vault status other than Active - the default status.
    /// @param vaults Addresses of vault proxy
    /// @param statuses New vault statuses. Constant from VaultStatusLib
    function setVaultStatus(address[] memory vaults, uint[] memory statuses) external;

    /// @notice Initial addition or change of strategy available init params
    /// @param id Strategy ID string
    /// @param initParams Init params variations that will be parsed by strategy
    function setStrategyAvailableInitParams(string memory id, StrategyAvailableInitParams memory initParams) external;

    /// @notice Assigns a new alias name to a specific address
    /// @dev This function may require certain permissions to be called successfully.
    /// @param tokenAddress_ The address to assign an alias name to
    /// @param aliasName_ The alias name to assign to the given address
    function setAliasName(address tokenAddress_, string memory aliasName_) external;

    //endregion -- Write functions -----
}

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

import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";

/// @notice The vaults are assembled at the factory by users through UI.
///         Deployment rights of a vault are tokenized in VaultManager NFT.
///         The holders of these tokens receive a share of the vault revenue and can manage vault if possible.
/// @dev Rewards transfers to token owner or revenue receiver address managed by token owner.
/// @author Alien Deployer (https://github.com/a17)
/// @author Jude (https://github.com/iammrjude)
/// @author JodsMigel (https://github.com/JodsMigel)
interface IVaultManager is IERC721Metadata {
    //region ----- Events -----
    event ChangeVaultParams(uint tokenId, address[] addresses, uint[] nums);
    event SetRevenueReceiver(uint tokenId, address receiver);
    //endregion -- Events -----

    struct VaultData {
        // vault
        uint tokenId;
        address vault;
        string vaultType;
        string name;
        string symbol;
        string[] assetsSymbols;
        string[] rewardAssetsSymbols;
        uint sharePrice;
        uint tvl;
        uint totalApr;
        bytes32 vaultExtra;
        // strategy
        uint strategyTokenId;
        string strategyId;
        string strategySpecific;
        uint strategyApr;
        bytes32 strategyExtra;
    }

    //region ----- View functions -----

    /// @notice Vault address managed by token
    /// @param tokenId ID of NFT. Starts from 0 and increments on mints.
    /// @return vault Address of vault proxy
    function tokenVault(uint tokenId) external view returns (address vault);

    /// @notice Receiver of token owner's platform revenue share
    /// @param tokenId ID of NFT
    /// @return receiver Address of vault manager fees receiver
    function getRevenueReceiver(uint tokenId) external view returns (address receiver);

    /// @notice All vaults data.
    /// The output values are matched by index in the arrays.
    /// @param vaultAddress Vault addresses
    /// @param name Vault name
    /// @param symbol Vault symbol
    /// @param vaultType Vault type ID string
    /// @param strategyId Strategy logic ID string
    /// @param sharePrice Current vault share price in USD. 18 decimals
    /// @param tvl Current vault TVL in USD. 18 decimals
    /// @param totalApr Last total vault APR. Denominator is 100_00.
    /// @param strategyApr Last strategy APR. Denominator is 100_00.
    /// @param strategySpecific Strategy specific name
    function vaults()
        external
        view
        returns (
            address[] memory vaultAddress,
            string[] memory name,
            string[] memory symbol,
            string[] memory vaultType,
            string[] memory strategyId,
            uint[] memory sharePrice,
            uint[] memory tvl,
            uint[] memory totalApr,
            uint[] memory strategyApr,
            string[] memory strategySpecific
        );

    /// @notice All deployed vault addresses
    /// @return vaultAddress Addresses of vault proxy
    function vaultAddresses() external view returns (address[] memory vaultAddress);

    /// @notice Vault extended info getter
    /// @param vault Address of vault proxy
    /// @return strategy
    /// @return strategyAssets
    /// @return underlying
    /// @return assetsWithApr Assets with underlying APRs that can be provided by AprOracle
    /// @return assetsAprs APRs of assets with APR. Matched by index wuth previous param.
    /// @return lastHardWork Last HardWork time
    function vaultInfo(address vault)
        external
        view
        returns (
            address strategy,
            address[] memory strategyAssets,
            address underlying,
            address[] memory assetsWithApr,
            uint[] memory assetsAprs,
            uint lastHardWork
        );

    //endregion -- View functions -----

    //region ----- Write functions -----

    /// @notice Changing managed vault init parameters by Vault Manager (owner of VaultManager NFT)
    /// @param tokenId ID of VaultManager NFT
    /// @param addresses Vault init addresses. Must contain also not changeable init addresses
    /// @param nums Vault init numbers. Must contant also not changeable init numbers
    function changeVaultParams(uint tokenId, address[] memory addresses, uint[] memory nums) external;

    /// @notice Minting of new token on deploying vault by Factory
    /// Only Factory can call this.
    /// @param to User which creates vault
    /// @param vault Address of vault proxy
    /// @return tokenId Minted token ID
    function mint(address to, address vault) external returns (uint tokenId);

    /// @notice Owner of token can change revenue reciever of platform fee share
    /// @param tokenId Owned token ID
    /// @param receiver New revenue receiver address
    function setRevenueReceiver(uint tokenId, address receiver) external;

    //endregion -- Write functions -----
}

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

import "./IStrategy.sol";

/// @notice Vault core interface.
/// Derived implementations can be effective for building tokenized vaults with single or multiple underlying liquidity mining position.
/// Fungible, static non-fungible and actively re-balancing liquidity is supported, as well as single token liquidity provided to lending protocols.
/// Vaults can be used for active concentrated liquidity management and market making.
/// @author Jude (https://github.com/iammrjude)
/// @author JodsMigel (https://github.com/JodsMigel)
interface IVault is IERC165 {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    error NotEnoughBalanceToPay();
    error FuseTrigger();
    error ExceedSlippage(uint mintToUser, uint minToMint);
    error ExceedSlippageExactAsset(address asset, uint mintToUser, uint minToMint);
    error ExceedMaxSupply(uint maxSupply);
    error NotEnoughAmountToInitSupply(uint mintAmount, uint initialShares);
    error WaitAFewBlocks();
    error StrategyZeroDeposit();
    error NotSupported();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           EVENTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    event DepositAssets(address indexed account, address[] assets, uint[] amounts, uint mintAmount);
    event WithdrawAssets(
        address indexed sender, address indexed owner, address[] assets, uint sharesAmount, uint[] amountsOut
    );
    event HardWorkGas(uint gasUsed, uint gasCost, bool compensated);
    event DoHardWorkOnDepositChanged(bool oldValue, bool newValue);
    event MaxSupply(uint maxShares);
    event VaultName(string newName);
    event VaultSymbol(string newSymbol);
    event MintFees(
        uint vaultManagerReceiverFee,
        uint strategyLogicReceiverFee,
        uint ecosystemRevenueReceiverFee,
        uint multisigReceiverFee
    );

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         DATA TYPES                         */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @custom:storage-location erc7201:stability.VaultBase
    struct VaultBaseStorage {
        /// @dev Prevents manipulations with deposit and withdraw in short time.
        ///      For simplification we are setup new withdraw request on each deposit/transfer.
        mapping(address msgSender => uint blockNumber) withdrawRequests;
        /// @inheritdoc IVault
        IStrategy strategy;
        /// @inheritdoc IVault
        uint maxSupply;
        /// @inheritdoc IVault
        uint tokenId;
        /// @inheritdoc IVault
        bool doHardWorkOnDeposit;
        /// @dev Immutable vault type ID
        string _type;
        /// @dev Changed ERC20 name
        string changedName;
        /// @dev Changed ERC20 symbol
        string changedSymbol;
    }

    /// @title Vault Initialization Data
    /// @notice Data structure containing parameters for initializing a new vault.
    /// @dev This struct is commonly used as a parameter for the `initialize` function in vault contracts.
    /// @param platform Platform address providing access control, infrastructure addresses, fee settings, and upgrade capability.
    /// @param strategy Immutable strategy proxy used by the vault.
    /// @param name ERC20 name for the vault token.
    /// @param symbol ERC20 symbol for the vault token.
    /// @param tokenId NFT ID associated with the VaultManager.
    /// @param vaultInitAddresses Array of addresses used during vault initialization.
    /// @param vaultInitNums Array of uint values corresponding to initialization parameters.
    struct VaultInitializationData {
        address platform;
        address strategy;
        string name;
        string symbol;
        uint tokenId;
        address[] vaultInitAddresses;
        uint[] vaultInitNums;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       VIEW FUNCTIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @notice Immutable vault type ID
    function vaultType() external view returns (string memory);

    /// @return uniqueInitAddresses Return required unique init addresses
    /// @return uniqueInitNums Return required unique init nums
    function getUniqueInitParamLength() external view returns (uint uniqueInitAddresses, uint uniqueInitNums);

    /// @notice Vault type extra data
    /// @return Vault type color, background color and other extra data
    function extra() external view returns (bytes32);

    /// @notice Immutable strategy proxy used by the vault
    /// @return Linked strategy
    function strategy() external view returns (IStrategy);

    /// @notice Max supply of shares in the vault.
    /// Since the starting share price is $1, this ceiling can be considered as an approximate TVL limit.
    /// @return Max total supply of vault
    function maxSupply() external view returns (uint);

    /// @dev VaultManager token ID. This tokenId earn feeVaultManager provided by Platform.
    function tokenId() external view returns (uint);

    /// @dev Trigger doHardwork on invest action. Enabled by default.
    function doHardWorkOnDeposit() external view returns (bool);

    /// @dev USD price of share with 18 decimals.
    ///      ONLY FOR OFF-CHAIN USE.
    ///      Not trusted vault share price can be manipulated.
    /// @return price_ Price of 1e18 shares with 18 decimals precision
    /// @return trusted True means oracle price, false means AMM spot price
    function price() external view returns (uint price_, bool trusted);

    /// @dev USD price of assets managed by strategy with 18 decimals
    ///      ONLY FOR OFF-CHAIN USE.
    ///      Not trusted TVL can be manipulated.
    /// @return tvl_ Total USD value of final assets in vault
    /// @return trusted True means TVL calculated based only on oracle prices, false means AMM spot price was used.
    function tvl() external view returns (uint tvl_, bool trusted);

    /// @dev Calculation of consumed amounts, shares amount and liquidity/underlying value for provided available amounts of strategy assets
    /// @param assets_ Assets suitable for vault strategy. Can be strategy assets, underlying asset or specific set of assets depending on strategy logic.
    /// @param amountsMax Available amounts of assets_ that user wants to invest in vault
    /// @return amountsConsumed Amounts of strategy assets that can be deposited by providing amountsMax
    /// @return sharesOut Amount of vault shares that will be minted
    /// @return valueOut Liquidity value or underlying token amount that will be received by the strategy
    function previewDepositAssets(
        address[] memory assets_,
        uint[] memory amountsMax
    ) external view returns (uint[] memory amountsConsumed, uint sharesOut, uint valueOut);

    /// @notice All available data on the latest declared APR (annual percentage rate)
    /// @return totalApr Total APR of investing money to vault. 18 decimals: 1e18 - +100% per year.
    /// @return strategyApr Strategy investmnt APR declared on last HardWork.
    /// @return assetsWithApr Assets with underlying APR
    /// @return assetsAprs Underlying APR of asset
    function getApr()
        external
        view
        returns (uint totalApr, uint strategyApr, address[] memory assetsWithApr, uint[] memory assetsAprs);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      WRITE FUNCTIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Mint fee shares callback
    /// @param revenueAssets Assets returned by _claimRevenue function that was earned during HardWork
    /// @param revenueAmounts Assets amounts returned from _claimRevenue function that was earned during HardWork
    /// Only strategy can call this
    function hardWorkMintFeeCallback(address[] memory revenueAssets, uint[] memory revenueAmounts) external;

    /// @dev Deposit final assets (pool assets) to the strategy and minting of vault shares.
    ///      If the strategy interacts with a pool or farms through an underlying token, then it will be minted.
    ///      Emits a {DepositAssets} event with consumed amounts.
    /// @param assets_ Assets suitable for the strategy. Can be strategy assets, underlying asset or specific set of assets depending on strategy logic.
    /// @param amountsMax Available amounts of assets_ that user wants to invest in vault
    /// @param minSharesOut Slippage tolerance. Minimal shares amount which must be received by user.
    /// @param receiver Receiver of deposit. If receiver is zero address, receiver is msg.sender.
    function depositAssets(
        address[] memory assets_,
        uint[] memory amountsMax,
        uint minSharesOut,
        address receiver
    ) external;

    /// @dev Burning shares of vault and obtaining strategy assets.
    /// @param assets_ Assets suitable for the strategy. Can be strategy assets, underlying asset or specific set of assets depending on strategy logic.
    /// @param amountShares Shares amount for burning
    /// @param minAssetAmountsOut Slippage tolerance. Minimal amounts of strategy assets that user must receive.
    /// @return Amount of assets for withdraw. It's related to assets_ one-by-one.
    function withdrawAssets(
        address[] memory assets_,
        uint amountShares,
        uint[] memory minAssetAmountsOut
    ) external returns (uint[] memory);

    /// @dev Burning shares of vault and obtaining strategy assets.
    /// @param assets_ Assets suitable for the strategy. Can be strategy assets, underlying asset or specific set of assets depending on strategy logic.
    /// @param amountShares Shares amount for burning
    /// @param minAssetAmountsOut Slippage tolerance. Minimal amounts of strategy assets that user must receive.
    /// @param receiver Receiver of assets
    /// @param owner Owner of vault shares
    /// @return Amount of assets for withdraw. It's related to assets_ one-by-one.
    function withdrawAssets(
        address[] memory assets_,
        uint amountShares,
        uint[] memory minAssetAmountsOut,
        address receiver,
        address owner
    ) external returns (uint[] memory);

    /// @dev Setting of vault capacity
    /// @param maxShares If totalSupply() exceeds this value, deposits will not be possible
    function setMaxSupply(uint maxShares) external;

    /// @dev If activated will call doHardWork on strategy on some deposit actions
    /// @param value HardWork on deposit is enabled
    function setDoHardWorkOnDeposit(bool value) external;

    /// @notice Initialization function for the vault.
    /// @dev This function is usually called by the Factory during the creation of a new vault.
    /// @param vaultInitializationData Data structure containing parameters for vault initialization.
    function initialize(VaultInitializationData memory vaultInitializationData) external;

    /// @dev Calling the strategy HardWork by operator with optional compensation for spent gas from the vault balance
    function doHardWork() external;

    /// @dev Changing ERC20 name of vault
    function setName(string calldata newName) external;

    /// @dev Changing ERC20 symbol of vault
    function setSymbol(string calldata newSymbol) external;
}

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

/// @dev HardWork resolver and caller. Primary executor is server script, reserve executor is Gelato Automate.
/// Hardwork is important task of any vault - claiming revenue and processing it by strategy, updating rewarding,
/// compounding, declaring income and losses, related things.
/// @author Alien Deployer (https://github.com/a17)
/// @author JodsMigel (https://github.com/JodsMigel)
interface IHardWorker {
    //region ----- Custom Errors -----
    error NotExistWithObject(address notExistObject);
    error AlreadyExclude(address alreadyExcludedObject);
    error NotServerOrGelato();
    error NotEnoughETH();
    //endregion ----- Custom Errors -----

    event Call(uint hardworks, uint gasUsed, uint gasCost, bool server);
    event DedicatedServerMsgSender(address indexed sender, bool allowed);
    event DedicatedGelatoMsgSender(address oldSender, address newSender);
    event Delays(uint delayServer, uint delayGelato);
    event GelatoTask(bytes32 id);
    event GelatoDeposit(uint amount);
    event MaxHwPerCall(uint maxHwPerCall_);
    event VaultExcludeStatusChanged(address vault, bool status);

    function getDelays() external view returns (uint delayServer, uint delayGelato);

    /// @notice Vaults that excluded from HardWork execution
    function excludedVaults(address vault) external view returns (bool);

    /// @notice Maximum vault HardWork calls per execution
    function maxHwPerCall() external view returns (uint);

    /// @notice Check dedicated server address allowance for execute vault HardWorks
    function dedicatedServerMsgSender(address sender) external view returns (bool allowed);

    /// @notice Dedicated Gelato OPS proxy for HardWorker contract address.
    /// OPS proxy is deployed at HardWorker initialization.
    /// @return Immutable Gelato dedicated msg.sender
    function dedicatedGelatoMsgSender() external view returns (address);

    /// @notice Checker method for calling from server script
    /// @return canExec Hard Work can be executed
    /// @return execPayload Vault addresses for HardWork
    function checkerServer() external view returns (bool canExec, bytes memory execPayload);

    /// @notice Checker method for calling from Gelato Automate
    /// @return canExec Hard Work can be executed
    /// @return execPayload Vault addresses for HardWork
    function checkerGelato() external view returns (bool canExec, bytes memory execPayload);

    /// @notice Gelato Automate task ID created by this contract
    function gelatoTaskId() external view returns (bytes32);

    /// @notice ETH balance of HardWork contract on Gelato
    /// @return ETH amount with 18 decimals
    function gelatoBalance() external view returns (uint);

    /// @notice Return minimum required ETH balance of HardWork contract on Gelato
    /// @return ETH amount with 18 decimals
    function gelatoMinBalance() external view returns (uint);

    /// @notice Setup allowance status for dedicated server address
    function setDedicatedServerMsgSender(address sender, bool allowed) external;

    /// @notice Setup delays between HardWorks in seconds
    /// @param delayServer_ Delay for server script
    /// @param delayGelato_ Delay for Gelato
    function setDelays(uint delayServer_, uint delayGelato_) external;

    /// @notice Set maximum vault HardWork calls per execution
    /// Only operator cal call this
    /// @param maxHwPerCall_ Max vault HardWorks per call(vaults) execution
    //slither-disable-next-line similar-names
    function setMaxHwPerCall(uint maxHwPerCall_) external;

    /// @notice Changing vault excluding status
    /// @param vaults_ Addresses of vaults
    /// @param status New status
    function changeVaultExcludeStatus(address[] memory vaults_, bool[] memory status) external;

    /// @notice Call vault HardWorks
    /// @param vaults Addresses of vault from checkerServer/checkerGelato output
    function call(address[] memory vaults) external;
}

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

import "./ITaskTreasuryUpgradable.sol";

enum Module {
    RESOLVER,
    TIME,
    PROXY,
    SINGLE_EXEC
}

struct ModuleData {
    Module[] modules;
    bytes[] args;
}

interface IAutomate {
    function createTask(
        address execAddress,
        bytes calldata execDataOrSelector,
        ModuleData calldata moduleData,
        address feeToken
    ) external returns (bytes32 taskId);

    function cancelTask(bytes32 taskId) external;

    function getFeeDetails() external view returns (uint, address);

    function gelato() external view returns (address payable);

    function taskTreasury() external view returns (ITaskTreasuryUpgradable);
}

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

interface IOpsProxyFactory {
    /**
     * @return address Proxy address owned by account.
     * @return bool Whether if proxy is deployed
     */
    function getProxyOf(address account) external view returns (address, bool);
}

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

interface ITaskTreasuryUpgradable {
    /// @notice Get balance of a token owned by user
    /// @param _user User to get balance from
    /// @param _token Token to check balance of
    function userTokenBalance(address _user, address _token) external view returns (uint);

    /// @notice Function to deposit Funds which will be used to execute transactions on various services
    /// @param receiver Address receiving the credits
    /// @param token Token to be credited, use "0xeeee...." for ETH
    /// @param amount Amount to be credited
    function depositFunds(address receiver, address token, uint amount) external payable;

    /// @notice Function to withdraw Funds back to the _receiver
    /// @param receiver Address receiving the credits
    /// @param token Token to be credited, use "0xeeee...." for ETH
    /// @param amount Amount to be credited
    function withdrawFunds(address payable receiver, address token, uint amount) external;
}

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

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

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

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return 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.
            return a / b;
        }

        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     * @dev 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 {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 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 prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

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

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, 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 {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

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

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            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^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // 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^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice 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) {
        uint256 result = mulDiv(x, y, denominator);
        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

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

    /**
     * @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 + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @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 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @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 + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
        }
    }

    /**
     * @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;
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

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

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

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

/// @title Minimal library for setting / getting slot variables (used in upgradable proxy contracts)
library SlotsLib {
    /// @dev Gets a slot as an address
    function getAddress(bytes32 slot) internal view returns (address result) {
        assembly {
            result := sload(slot)
        }
    }

    /// @dev Gets a slot as uint256
    function getUint(bytes32 slot) internal view returns (uint result) {
        assembly {
            result := sload(slot)
        }
    }

    /// @dev Sets a slot with address
    /// @notice Check address for 0 at the setter
    function set(bytes32 slot, address value) internal {
        assembly {
            sstore(slot, value)
        }
    }

    /// @dev Sets a slot with uint
    function set(bytes32 slot, uint value) internal {
        assembly {
            sstore(slot, value)
        }
    }
}

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

/// @dev Base core interface implemented by most platform contracts.
///      Inherited contracts store an immutable Platform proxy address in the storage,
///      which provides authorization capabilities and infrastructure contract addresses.
/// @author Alien Deployer (https://github.com/a17)
/// @author JodsMigel (https://github.com/JodsMigel)
interface IControllable {
    //region ----- Custom Errors -----
    error IncorrectZeroArgument();
    error IncorrectMsgSender();
    error NotGovernance();
    error NotMultisig();
    error NotGovernanceAndNotMultisig();
    error NotOperator();
    error NotFactory();
    error NotPlatform();
    error NotVault();
    error IncorrectArrayLength();
    error AlreadyExist();
    error NotExist();
    error NotTheOwner();
    error ETHTransferFailed();
    error IncorrectInitParams();
    //endregion -- Custom Errors -----

    event ContractInitialized(address platform, uint ts, uint block);

    /// @notice Stability Platform main contract address
    function platform() external view returns (address);

    /// @notice Version of contract implementation
    /// @dev SemVer scheme MAJOR.MINOR.PATCH
    //slither-disable-next-line naming-convention
    function VERSION() external view returns (string memory);

    /// @notice Block number when contract was initialized
    function createdBlock() external view returns (uint);
}

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

pragma solidity ^0.8.20;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

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

import "@openzeppelin/contracts/utils/introspection/IERC165.sol";

/// @dev Core interface of strategy logic
interface IStrategy is IERC165 {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           EVENTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    event HardWork(
        uint apr, uint compoundApr, uint earned, uint tvl, uint duration, uint sharePrice, uint[] assetPrices
    );
    event ExtractFees(
        uint vaultManagerReceiverFee,
        uint strategyLogicReceiverFee,
        uint ecosystemRevenueReceiverFee,
        uint multisigReceiverFee
    );

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    error NotReadyForHardWork();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         DATA TYPES                         */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @custom:storage-location erc7201:stability.StrategyBase
    struct StrategyBaseStorage {
        /// @inheritdoc IStrategy
        address vault;
        /// @inheritdoc IStrategy
        uint total;
        /// @inheritdoc IStrategy
        uint lastHardWork;
        /// @inheritdoc IStrategy
        uint lastApr;
        /// @inheritdoc IStrategy
        uint lastAprCompound;
        /// @inheritdoc IStrategy
        address[] _assets;
        /// @inheritdoc IStrategy
        address _underlying;
        string _id;
        uint _exchangeAssetIndex;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       VIEW FUNCTIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Strategy logic string ID
    function strategyLogicId() external view returns (string memory);

    /// @dev Extra data
    /// @return 0-2 bytes - strategy color
    ///         3-5 bytes - strategy background color
    ///         6-31 bytes - free
    function extra() external view returns (bytes32);

    /// @dev Types of vault that supported by strategy implementation
    /// @return types Vault type ID strings
    function supportedVaultTypes() external view returns (string[] memory types);

    /// @dev Linked vault address
    function vault() external view returns (address);

    /// @dev Final assets that strategy invests
    function assets() external view returns (address[] memory);

    /// @notice Final assets and amounts that strategy manages
    function assetsAmounts() external view returns (address[] memory assets_, uint[] memory amounts_);

    /// @notice Priced invested assets proportions
    /// @return proportions Proportions of assets with 18 decimals. Min is 0, max is 1e18.
    function getAssetsProportions() external view returns (uint[] memory proportions);

    /// @notice Underlying token address
    /// @dev Can be used for liquidity farming strategies where AMM has fungible liquidity token (Solidly forks, etc),
    ///      for concentrated liquidity tokenized vaults (Gamma, G-UNI etc) and for other needs.
    /// @return Address of underlying token or zero address if no underlying in strategy
    function underlying() external view returns (address);

    /// @dev Balance of liquidity token or liquidity value
    function total() external view returns (uint);

    /// @dev Last HardWork time
    /// @return Timestamp
    function lastHardWork() external view returns (uint);

    /// @dev Last APR of earned USD amount registered by HardWork
    ///      ONLY FOR OFF-CHAIN USE.
    ///      Not trusted asset price can be manipulated.
    /// @return APR with 18 decimals. 1e18 - 100%.
    function lastApr() external view returns (uint);

    /// @dev Last APR of compounded assets registered by HardWork.
    ///      Can be used on-chain.
    /// @return APR with 18 decimals. 1e18 - 100%.
    function lastAprCompound() external view returns (uint);

    /// @notice Calculation of consumed amounts and liquidity/underlying value for provided strategy assets and amounts.
    /// @param assets_ Strategy assets or part of them, if necessary
    /// @param amountsMax Amounts of specified assets available for investing
    /// @return amountsConsumed Cosumed amounts of assets when investing
    /// @return value Liquidity value or underlying token amount minted when investing
    function previewDepositAssets(
        address[] memory assets_,
        uint[] memory amountsMax
    ) external view returns (uint[] memory amountsConsumed, uint value);

    /// @notice Write version of previewDepositAssets
    /// @param assets_ Strategy assets or part of them, if necessary
    /// @param amountsMax Amounts of specified assets available for investing
    /// @return amountsConsumed Cosumed amounts of assets when investing
    /// @return value Liquidity value or underlying token amount minted when investing
    function previewDepositAssetsWrite(
        address[] memory assets_,
        uint[] memory amountsMax
    ) external returns (uint[] memory amountsConsumed, uint value);

    /// @notice All strategy revenue (pool fees, farm rewards etc) that not claimed by strategy yet
    /// @return assets_ Revenue assets
    /// @return amounts Amounts. Index of asset same as in previous array.
    function getRevenue() external view returns (address[] memory assets_, uint[] memory amounts);

    /// @notice Optional specific name of investing strategy, underyling type, setup variation etc
    /// @return name Empty string or specific name
    /// @return showInVaultSymbol Show specific in linked vault symbol
    function getSpecificName() external view returns (string memory name, bool showInVaultSymbol);

    /// @notice Variants pf strategy initializations with description of money making mechanic.
    /// As example, if strategy need farm, then number of variations is number of available farms.
    /// If CAMM strategy have set of available widths (tick ranges), then number of variations is number of available farms.
    /// If both example conditions are met then total number or variations = total farms * total widths.
    /// @param platform_ Need this param because method called when strategy implementation is not initialized
    /// @return variants Descriptions of the strategy for making money
    /// @return addresses Init strategy addresses. Indexes for each variants depends of copmpared arrays lengths.
    /// @return nums Init strategy numbers. Indexes for each variants depends of copmpared arrays lengths.
    /// @return ticks Init strategy ticks. Indexes for each variants depends of copmpared arrays lengths.
    function initVariants(address platform_)
        external
        view
        returns (string[] memory variants, address[] memory addresses, uint[] memory nums, int24[] memory ticks);

    /// @notice How does the strategy make money?
    /// @return Description in free form
    function description() external view returns (string memory);

    /// @notice Is HardWork on vault deposits can be enabled
    function isHardWorkOnDepositAllowed() external view returns (bool);

    /// @notice Is HardWork can be executed
    function isReadyForHardWork() external view returns (bool);

    /// @notice Strategy not need to process revenue on HardWorks
    function autoCompoundingByUnderlyingProtocol() external view returns (bool);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      WRITE FUNCTIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev A single universal initializer for all strategy implementations.
    /// @param addresses All addresses that strategy requires for initialization. Min array length is 2.
    ///        addresses[0]: platform (required)
    ///        addresses[1]: vault (required)
    ///        addresses[2]: initStrategyAddresses[0] (optional)
    ///        addresses[3]: initStrategyAddresses[1] (optional)
    ///        addresses[n]: initStrategyAddresses[n - 2] (optional)
    /// @param nums All uint values that strategy requires for initialization. Min array length is 0.
    /// @param ticks All int24 values that strategy requires for initialization. Min array length is 0.
    function initialize(address[] memory addresses, uint[] memory nums, int24[] memory ticks) external;

    /// @notice Invest strategy assets. Amounts of assets must be already on strategy contract balance.
    /// Only vault can call this.
    /// @param amounts Anounts of strategy assets
    /// @return value Liquidity value or underlying token amount
    function depositAssets(uint[] memory amounts) external returns (uint value);

    /// @notice Invest underlying asset. Asset must be already on strategy contract balance.
    /// Only vault can call this.
    /// @param amount Amount of underlying asset to invest
    /// @return amountsConsumed Cosumed amounts of invested assets
    function depositUnderlying(uint amount) external returns (uint[] memory amountsConsumed);

    /// @dev For specified amount of shares and assets_, withdraw strategy assets from farm/pool/staking and send to receiver if possible
    /// Only vault can call this.
    /// @param assets_ Here we give the user a choice of assets to withdraw if strategy support it
    /// @param value Part of strategy total value to withdraw
    /// @param receiver User address
    /// @return amountsOut Amounts of assets sent to user
    function withdrawAssets(
        address[] memory assets_,
        uint value,
        address receiver
    ) external returns (uint[] memory amountsOut);

    /// @notice Wothdraw underlying invested and send to receiver
    /// Only vault can call this.
    /// @param amount Ampunt of underlying asset to withdraw
    /// @param receiver User of vault which withdraw underlying from the vault
    function withdrawUnderlying(uint amount, address receiver) external;

    /// @dev For specified amount of shares, transfer strategy assets from contract balance and send to receiver if possible
    /// This method is called by vault w/o underlying on triggered fuse mode.
    /// Only vault can call this.
    /// @param amount Ampunt of liquidity value that user withdraw
    /// @param totalAmount Total amount of strategy liquidity
    /// @param receiver User of vault which withdraw assets
    /// @return amountsOut Amounts of strategy assets sent to user
    function transferAssets(
        uint amount,
        uint totalAmount,
        address receiver
    ) external returns (uint[] memory amountsOut);

    /// @notice Execute HardWork
    /// During HardWork strategy claiming revenue and processing it.
    /// Only vault can call this.
    function doHardWork() external;

    /// @notice Emergency stop investing by strategy, withdraw liquidity without rewards.
    /// This action triggers FUSE mode.
    /// Only governance or multisig can call this.
    function emergencyStopInvesting() external;
}

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * 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[EIP 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);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
     *   {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

Please enter a contract address above to load the contract details and source code.

Context size (optional):