// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: @openzeppelin/contracts/security/ReentrancyGuard.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

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

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

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

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

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

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

// File: @openzeppelin/contracts/token/ERC20/ERC20.sol



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

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

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

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

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

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

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

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

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

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

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

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

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(address from, address to, uint256 amount) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

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

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}

// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

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

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

// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

// File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol



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

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";

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

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

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

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Compatible with tokens that require the approval to be set to
     * 0 before setting it to a non-zero value.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

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

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}

// File: @openzeppelin/contracts/utils/Address.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

// File: @openzeppelin/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

// File: @openzeppelin/contracts/utils/math/Math.sol



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

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @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 up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (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; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                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.
            require(denominator > prod1, "Math: mulDiv overflow");

            ///////////////////////////////////////////////
            // 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.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            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 (rounding == Rounding.Up && 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 down.
     *
     * 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 + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * 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 + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * 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 + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * 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 + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
        }
    }
}

// File: @openzeppelin/contracts/utils/math/SafeMath.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/SafeMath.sol)

pragma solidity ^0.8.0;

// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.

/**
 * @dev Wrappers over Solidity's arithmetic operations.
 *
 * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
 * now has built in overflow checking.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    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.
     *
     * _Available since v3.4._
     */
    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.
     *
     * _Available since v3.4._
     */
    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.
     *
     * _Available since v3.4._
     */
    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.
     *
     * _Available since v3.4._
     */
    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 addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        return a + b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        return a * b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator.
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b <= a, errorMessage);
            return a - b;
        }
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a / b;
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a % b;
        }
    }
}

// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol



//SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.5.0;

interface IUniswapV2Factory {
    event PairCreated(address indexed token0, address indexed token1, address pair, uint);

    function feeTo() external view returns (address);
    function feeToSetter() external view returns (address);

    function getPair(address tokenA, address tokenB) external view returns (address pair);
    function allPairs(uint) external view returns (address pair);
    function allPairsLength() external view returns (uint);

    function createPair(address tokenA, address tokenB) external returns (address pair);

    function setFeeTo(address) external;
    function setFeeToSetter(address) external;
}

// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol



//SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.5.0;

interface IUniswapV2Pair {
    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    function name() external pure returns (string memory);
    function symbol() external pure returns (string memory);
    function decimals() external pure returns (uint8);
    function totalSupply() external view returns (uint);
    function balanceOf(address owner) external view returns (uint);
    function allowance(address owner, address spender) external view returns (uint);

    function approve(address spender, uint value) external returns (bool);
    function transfer(address to, uint value) external returns (bool);
    function transferFrom(address from, address to, uint value) external returns (bool);

    function DOMAIN_SEPARATOR() external view returns (bytes32);
    function PERMIT_TYPEHASH() external pure returns (bytes32);
    function nonces(address owner) external view returns (uint);

    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;

    event Mint(address indexed sender, uint amount0, uint amount1);
    event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
    event Swap(
        address indexed sender,
        uint amount0In,
        uint amount1In,
        uint amount0Out,
        uint amount1Out,
        address indexed to
    );
    event Sync(uint112 reserve0, uint112 reserve1);

    function MINIMUM_LIQUIDITY() external pure returns (uint);
    function factory() external view returns (address);
    function token0() external view returns (address);
    function token1() external view returns (address);
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
    function price0CumulativeLast() external view returns (uint);
    function price1CumulativeLast() external view returns (uint);
    function kLast() external view returns (uint);

    function mint(address to) external returns (uint liquidity);
    function burn(address to) external returns (uint amount0, uint amount1);
    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
    function skim(address to) external;
    function sync() external;

    function initialize(address, address) external;
}

// File: contracts/CIV-TimeOracle.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

/// @title TimeOracle
/// @author Civilization
/// @notice This contract is used to track periods of time based on a given epoch duration
/// @dev The owner of the contract can change the epoch duration
contract TimeOracle {
    address public owner; // Owner of the contract
    uint public startTime; // Start time of the tracking
    uint public epochDuration; // Duration of each period in seconds
    uint public currentPeriod; // Current periods elapsed from the start

    /// @notice Initializes the contract with a given epoch duration
    /// @param _epochDuration Duration of each period in seconds
    constructor(uint _epochDuration) {
        owner = msg.sender; // Set the deployer as the owner
        startTime = block.timestamp; // Initialization at deployment time
        epochDuration = _epochDuration;
    }

    /// @notice Calculates the start time for current period
    /// @return currentPeriodStartTime The start time for the current period
    function getCurrentPeriod()
        external
        view
        returns (uint currentPeriodStartTime)
    {
        require(
            block.timestamp >= startTime,
            "TimeOracle: Query before start time"
        );

        // Calculate how many periods have passed since the start
        uint period = (block.timestamp - startTime) /
            epochDuration;

        // Calculate the start time for the current period
        currentPeriodStartTime = startTime + period * epochDuration;

        return currentPeriodStartTime;
    }

    /// @notice Allows the owner to set a new epoch duration
    /// @param _newEpochDuration The new epoch duration in seconds
    function setEpochDuration(uint _newEpochDuration) external {
        require(
            msg.sender == owner,
            "TimeOracle: Only owner can change epochDuration"
        );

        // Calculate the current period before changing epochDuration
        currentPeriod += (block.timestamp - startTime) / epochDuration;

        // Update startTime to now
        startTime = block.timestamp;

        // Update epochDuration
        epochDuration = _newEpochDuration;
    }
}

// File: contracts/CIV-Vault.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

/**
 * @title  Civ Vault
 * @author Ren / Frank
 */

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./dependencies/FixedPoint.sol";
import "./interfaces/ICivFund.sol";
import "./CIV-VaultGetter.sol";
import "./CIV-VaultFactory.sol";

contract CIVVault is Ownable, ReentrancyGuard {
    using SafeERC20 for IERC20;
    using SafeERC20 for ICivFundRT;
    using FixedPoint for *;

    /// @notice All Fees Base Amount
    uint public constant feeBase = 10_000;
    /// @notice Safety Factor to avoid out of Gas in loops
    uint public gasBuffer;
    /// @notice Number of strategies
    uint public strategiesCounter;
    /// @notice vault getter contract
    ICivVaultGetter public vaultGetter;
    /// @notice share factory contract
    CIVFundShareFactory public fundShareFactory;
    /// @notice mapping with info on each strategy
    mapping(uint => StrategyInfo) private _strategyInfo;
    /// @notice structure with epoch info
    mapping(uint => mapping(uint => EpochInfo)) private _epochInfo;
    /// @notice Info of each user that enters the fund
    mapping(uint => mapping(address => UserInfo)) private _userInfo;
    /// @notice Counter for the epochs of each strategy
    mapping(uint => uint) private _epochCounter;
    /// @notice Each Strategies epoch informations per address
    mapping(uint => mapping(address => mapping(uint => UserInfoEpoch)))
        private _userInfoEpoch;
    /// @notice Mapping of depositors on a particular epoch
    mapping(uint => mapping(uint => mapping(uint => address)))
        private _depositors;
    /// @notice Mapping of guarantee locks on a strategy for each user
    mapping(uint => mapping(address => mapping(uint => GuaranteeInfo)))
        private _userGuaranteeLock; // Index of the depositor in the depositors mapping

    ////////////////// EVENTS //////////////////

    /// @notice Event emitted when user deposit fund to our vault or vault deposit fund to strategy
    event Deposit(
        address indexed user,
        address receiver,
        uint indexed id,
        uint amount
    );
    /// @notice Event emitted when user request withdraw fund from our vault or vault withdraw fund to user
    event Withdraw(address indexed user, uint indexed id, uint amount);
    /// @notice Event emitted when owner sets new fee
    event SetFee(
        uint id,
        uint oldFee,
        uint newFee,
        uint oldDuration,
        uint newDuration
    );
    /// @notice Event emitted when owner sets new guarantee fee
    event SetGuaranteeFee(uint oldFee, uint newFee);
    /// @notice Event emitted when owner sets new gas buffer
    event SetGasBuffer(uint gasBuffer, uint newGasBuffer);
    /// @notice Event emitted when owner sets new deposit duration
    event SetEpochDuration(uint id, uint oldDuration, uint newDuration);
    /// @notice Event emitted when owner sets new guarantee token lock time
    event SetGuaranteeLockTime(uint id, uint oldLocktime, uint newLockTime);
    /// @notice Event emitted when owner sets new treasury addresses
    event SetWithdrawAddress(
        uint id,
        address[] oldAddress,
        address[] newAddress
    );
    /// @notice Event emitted when owner sets new invest address
    event SetInvestAddress(uint id, address oldAddress, address newAddress);
    /// @notice Event emitted when send fee to our treasury
    event SendFeeWithOwner(uint id, address treasuryAddress, uint feeAmount);
    /// @notice Event emitted when owner update new VPS
    event UpdateVPS(uint id, uint lastEpoch, uint VPS);
    /// @notice Event emitted when owner paused deposit
    event SetPaused(uint id, bool paused);
    /// @notice Event emitted when owner set new Max & Min Deposit Amount
    event SetLimits(
        uint id,
        uint oldMaxAmount,
        uint newMaxAmount,
        uint oldMinAmount,
        uint newMinAmount,
        uint oldMaxUsers,
        uint newMaxUsers
    );
    /// @notice Event emitted when user cancel pending deposit from vault
    event CancelDeposit(address user, uint id, uint amount);
    /// @notice Event emitted when user cancel withdraw request from vault
    event CancelWithdraw(address user, uint id, uint amount);
    /// @notice Event emitted when Uniswap Token Price Updated
    event Update(uint id, uint index);
    /// @notice Event emitted when user claim guarantee token
    event ClaimGuarantee(uint id, address user, uint guaranteeAmount);
    /// @notice Event emitted when user claim Asset token for each epoch
    event ClaimWithdrawedToken(
        uint id,
        address user,
        uint epoch,
        uint assetAmount
    );
    /// @notice Event emitted when user claim Asset token
    event WithdrawedToken(uint id, address user, uint assetAmount);
    /// @notice Event emitted when owner adds new strategy
    event AddStrategy(
        uint indexed id,
        uint indexed fee,
        uint maxDeposit,
        uint minDeposit,
        bool paused,
        address[] withdrawAddress,
        address assetToken,
        address guaranteeToken,
        uint lockPeriod,
        uint feeDuration
    );
    /// @notice Event emitted when strategy is initialized
    event InitializeStrategy(uint indexed id);

    ////////////////// ERROR CODES //////////////////
    /*
    ERR_V.1 = "Strategy does not exist";
    ERR_V.2 = "Deposit paused";
    ERR_V.3 = "Treasury Address Length must be 2";
    ERR_V.4 = "Burn failed";
    ERR_V.5 = "Guarantee Token address cannot be null address";
    ERR_V.6 = "First Treasury address cannot be null address";
    ERR_V.7 = "Second Treasury address cannot be null address";
    ERR_V.8 = "Minting failed";
    ERR_V.9 = "Strategy already initialized";
    ERR_V.10 = "No epochs exist";
    ERR_V.11 = "Wait for the previos epoch to settle before requesting withdraw";
    ERR_V.12 = "Insufficient contract balance";
    ERR_V.13 = "Not enough amount to withdraw";
    ERR_V.14 = "Strategy address cannot be null address";
    ERR_V.15 = "Enable withdraw for previous epoch";
    ERR_V.16 = "Distribute all shares for previous epoch";
    ERR_V.17 = "Epoch does not exist";
    ERR_V.18 = "Epoch not yet expired";
    ERR_V.19 = "No funds available to withdraw";
    ERR_V.20 = "Amount can't be 0";
    ERR_V.21 = "Insufficient User balance";
    ERR_V.22 = "No more users are allowed";
    ERR_V.23 = "Deposit amount exceeds epoch limit";
    ERR_V.24 = "Epoch expired";
    ERR_V.25 = "Current balance not enough";
    ERR_V.26 = "Not enough total withdrawals";
    ERR_V.27 = "VPS not yet updated";
    ERR_V.28 = "Already started distribution";
    ERR_V.29 = "Not yet distributed";
    ERR_V.30 = "Already distributed";
    ERR_V.31 = "Fee duration not yet passed";
    ERR_V.32 = "Vault balance is not enough to pay fees";
    ERR_V.33 = "Transfer Failed";
    ERR_V.34 = "Withdraw Token cannot be deposit token";
    ERR_V.35 = "No pending Fees to distribute";
    ERR_V.36 = "Nothing to claim";
    ERR_V.37 = "Wait for rebalancing to complete";
    */

    ////////////////// MODIFIER //////////////////

    modifier checkStrategyExistence(uint _id) {
        require(strategiesCounter > _id, "ERR_V.1");
        _;
    }

    modifier checkEpochExistence(uint _id) {
        require(_epochCounter[_id] > 0, "ERR_V.10");
        _;
    }

    ////////////////// CONSTRUCTOR //////////////////

    constructor() {
        CivVaultGetter getterContract = new CivVaultGetter(address(this));
        fundShareFactory = new CIVFundShareFactory();
        vaultGetter = ICivVaultGetter(address(getterContract));
    }

    ////////////////// INITIALIZATION //////////////////

    /// @notice Add new strategy to our vault
    /// @dev Only Owner can call this function
    /// @param addStrategyParam Parameters for new strategy
    function addStrategy(
        AddStrategyParam memory addStrategyParam
    ) external virtual nonReentrant onlyOwner {
        require(addStrategyParam._withdrawAddresses.length == 2, "ERR_V.3");
        require(
            address(addStrategyParam._guaranteeToken) != address(0),
            "ERR_V.5"
        );
        require(
            addStrategyParam._withdrawAddresses[0] != address(0),
            "ERR_V.6"
        );
        require(
            addStrategyParam._withdrawAddresses[1] != address(0),
            "ERR_V.7"
        );
        /// deploy new CIVFundShare contract
        CIVFundShare fundRepresentToken = fundShareFactory.createCIVFundShare();

        _strategyInfo[strategiesCounter] = StrategyInfo({
            assetToken: addStrategyParam._assetToken,
            fundRepresentToken: ICivFundRT(address(fundRepresentToken)),
            guaranteeToken: addStrategyParam._guaranteeToken,
            fee: addStrategyParam._fee,
            guaranteeFee: addStrategyParam._guaranteeFee,
            withdrawAddress: addStrategyParam._withdrawAddresses,
            investAddress: addStrategyParam._investAddress,
            initialized: false,
            pendingFees: 0,
            maxDeposit: addStrategyParam._maxDeposit,
            maxUsers: addStrategyParam._maxUsers,
            minDeposit: addStrategyParam._minAmount,
            paused: addStrategyParam._paused,
            epochDuration: addStrategyParam._epochDuration,
            lockPeriod: addStrategyParam._lockPeriod,
            feeDuration: addStrategyParam._feeDuration,
            lastFeeDistribution: 0,
            lastProcessedEpoch: 0,
            watermark: 0
        });

        uint id = strategiesCounter;
        strategiesCounter++;
        vaultGetter.addUniPair(
            id,
            address(addStrategyParam._assetToken),
            address(addStrategyParam._guaranteeToken)
        );
        emit AddStrategy(
            id,
            addStrategyParam._fee,
            addStrategyParam._maxDeposit,
            addStrategyParam._minAmount,
            addStrategyParam._paused,
            addStrategyParam._withdrawAddresses,
            address(addStrategyParam._assetToken),
            address(addStrategyParam._guaranteeToken),
            addStrategyParam._lockPeriod,
            addStrategyParam._feeDuration
        );
    }

    /// @notice Delayed strategy start
    /// @dev Only Owner can call this function
    /// @param _id strategy id
    function initializeStrategy(
        uint _id
    ) external onlyOwner checkStrategyExistence(_id) {
        require(!_strategyInfo[_id].initialized, "ERR_V.9");

        _strategyInfo[_id].initialized = true;
        vaultGetter.addTimeOracle(_id, _strategyInfo[_id].epochDuration);

        _epochInfo[_id][_epochCounter[_id]] = EpochInfo({
            totDepositors: 0,
            totDepositedAssets: 0,
            totWithdrawnShares: 0,
            VPS: 0,
            newShares: 0,
            currentWithdrawAssets: 0,
            epochStartTime: block.timestamp,
            lastDepositorProcessed: 0,
            duration: _strategyInfo[_id].epochDuration
        });

        _epochCounter[_id]++;
        emit InitializeStrategy(_id);
    }

    ////////////////// SETTER //////////////////

    /// @notice Sets new fee and new collecting fee duration
    /// @dev Only Owner can call this function
    /// @param _id Strategy Id
    /// @param _newFee New Fee Percent
    /// @param _newDuration New Collecting Fee Duration
    function setFee(
        uint _id,
        uint _newFee,
        uint _newDuration
    ) external onlyOwner checkStrategyExistence(_id) {
        emit SetFee(
            _id,
            _strategyInfo[_id].fee,
            _newFee,
            _strategyInfo[_id].feeDuration,
            _newDuration
        );
        _strategyInfo[_id].fee = _newFee;
        _strategyInfo[_id].feeDuration = _newDuration;
    }

    /// @notice Sets new Strategy guarantee token lock time and guarantee fee
    /// @dev Only Owner can call this function
    /// @param _id Strategy Id
    /// @param _lockTime New Guarantee token lock time
    /// @param _newFee new guarantee fee amount
    function setStrategyGuarantee(
        uint _id,
        uint _lockTime,
        uint _newFee
    ) external onlyOwner checkStrategyExistence(_id) {
        emit SetGuaranteeLockTime(
            _id,
            _strategyInfo[_id].lockPeriod,
            _lockTime
        );
        emit SetGuaranteeFee(_strategyInfo[_id].guaranteeFee, _newFee);
        _strategyInfo[_id].lockPeriod = _lockTime;
        _strategyInfo[_id].guaranteeFee = _newFee;
    }

    /// @notice Sets new deposit fund from vault to strategy duration
    /// @dev Only Owner can call this function
    /// @param _id Strategy Id
    /// @param _newDuration New Duration for Deposit fund from vault to strategy
    function setEpochDuration(
        uint _id,
        uint _newDuration
    ) external onlyOwner checkStrategyExistence(_id) {
        emit SetEpochDuration(
            _id,
            _strategyInfo[_id].epochDuration,
            _newDuration
        );
        vaultGetter.setEpochDuration(_id, _newDuration);
        _strategyInfo[_id].epochDuration = _newDuration;
    }

    /// @notice Sets new treasury addresses to keep fee
    /// @dev Only Owner can call this function
    /// @param _id Strategy Id
    /// @param _newAddress Address list to keep fee
    function setWithdrawAddress(
        uint _id,
        address[] memory _newAddress
    ) external onlyOwner checkStrategyExistence(_id) {
        require(_newAddress.length == 2, "ERR_V.3");
        require(_newAddress[0] != address(0), "ERR_V.6");
        require(_newAddress[1] != address(0), "ERR_V.7");
        emit SetWithdrawAddress(
            _id,
            _strategyInfo[_id].withdrawAddress,
            _newAddress
        );
        _strategyInfo[_id].withdrawAddress = _newAddress;
    }

    /// @notice Sets new treasury addresses to keep fee
    /// @dev Only Owner can call this function
    /// @param _id Strategy Id
    /// @param _newAddress Address list to keep fee
    function setInvestAddress(
        uint _id,
        address _newAddress
    ) external onlyOwner checkStrategyExistence(_id) {
        require(_newAddress != address(0), "ERR_V.14");
        emit SetInvestAddress(
            _id,
            _strategyInfo[_id].investAddress,
            _newAddress
        );
        _strategyInfo[_id].investAddress = _newAddress;
    }

    /// @notice Set Pause of Unpause for deposit to vault
    /// @dev Only Owner can change this status
    /// @param _id Strategy Id
    /// @param _paused paused or unpaused for deposit
    function setPaused(
        uint _id,
        bool _paused
    ) external onlyOwner checkStrategyExistence(_id) {
        emit SetPaused(_id, _paused);
        _strategyInfo[_id].paused = _paused;
    }

    /// @notice Set limits on a given strategy
    /// @dev Only Owner can change this status
    /// @param _id Strategy Id
    /// @param _newMaxDeposit New Max Deposit Amount
    /// @param _newMinDeposit New Min Deposit Amount
    /// @param _newMaxUsers New Max User Count
    function setEpochLimits(
        uint _id,
        uint _newMaxDeposit,
        uint _newMinDeposit,
        uint _newMaxUsers
    ) external onlyOwner checkStrategyExistence(_id) {
        emit SetLimits(
            _id,
            _strategyInfo[_id].maxDeposit,
            _newMaxDeposit,
            _strategyInfo[_id].minDeposit,
            _newMinDeposit,
            _strategyInfo[_id].maxUsers,
            _newMaxUsers
        );
        _strategyInfo[_id].maxDeposit = _newMaxDeposit;
        _strategyInfo[_id].minDeposit = _newMinDeposit;
        _strategyInfo[_id].maxUsers = _newMaxUsers;
    }

    /// @notice Sets new gas buffer
    /// @dev Only Owner can call this function
    /// @param _gasBuffer new gas buffer amount
    function setGasBuffer(uint _gasBuffer) external onlyOwner {
        emit SetGasBuffer(gasBuffer, _gasBuffer);
        gasBuffer = _gasBuffer;
    }

    ////////////////// GETTER //////////////////

    /**
     * @dev Fetches the strategy information for a given strategy _id.
     * @param _id The ID of the strategy to fetch the information for.
     * @return strategy The StrategyInfo struct associated with the provided _id.
     */
    function getStrategyInfo(
        uint _id
    )
        external
        view
        checkStrategyExistence(_id)
        returns (StrategyInfo memory strategy)
    {
        strategy = _strategyInfo[_id];
    }

    /**
     * @dev Fetches the epoch information for a given strategy _id.
     * @param _id The ID of the strategy to fetch the information for.
     * @param _index The index of the epoch to fetch the information for.
     * @return epoch The EpochInfo struct associated with the provided _id and _index.
     */
    function getEpochInfo(
        uint _id,
        uint _index
    )
        external
        view
        checkStrategyExistence(_id)
        checkEpochExistence(_id)
        returns (EpochInfo memory epoch)
    {
        epoch = _epochInfo[_id][_index];
    }

    /**
     * @dev Fetches the current epoch number for a given strategy _id.
     * The current epoch is determined as the last index of the epochInfo mapping for the strategy.
     * @param _id The _id of the strategy to fetch the current epoch for.
     * @return The current epoch number for the given strategy _id.
     */
    function getCurrentEpoch(
        uint _id
    )
        public
        view
        checkStrategyExistence(_id)
        checkEpochExistence(_id)
        returns (uint)
    {
        return _epochCounter[_id] - 1;
    }

    /**
     * @dev Fetches the user information for a given strategy _id.
     * @param _id The _id of the strategy to fetch the information for.
     * @param _user The address of the user to fetch the information for.
     * @return user The UserInfo struct associated with the provided _id and _user.
     */
    function getUserInfo(
        uint _id,
        address _user
    ) external view checkStrategyExistence(_id) returns (UserInfo memory user) {
        user = _userInfo[_id][_user];
    }

    /**
     * @dev Fetches the user information for a given strategy _id.
     * @param _id The _id of the strategy to fetch the information for.
     * @param _epoch The starting index to fetch the information for.
     * @return users An array of addresses of unique depositors.
     */
    function getDepositors(
        uint _id,
        uint _epoch
    )
        external
        view
        checkStrategyExistence(_id)
        returns (address[] memory users)
    {  
        // Initialize the return array with the size equal to the range between the start and end indices
        users = new address[](_epochInfo[_id][_epoch].totDepositors);

        // Loop through the mapping to populate the return array
        for (uint i = 0; i < _epochInfo[_id][_epoch].totDepositors; i++) {
            users[i] = _depositors[_id][_epoch][i];
        }
    }

    /**
     * @dev Fetches the deposit parameters for a given strategy _id.
     * @param _id The _id of the strategy to fetch the information for.
     * @param _user The address of the user to fetch the information for.
     * @param _index The index of the deposit to fetch the information for.
     * @return userEpochStruct The UserInfoEpoch struct associated with the provided _id, _user and _index.
     */
    function getUserInfoEpoch(
        uint _id,
        address _user,
        uint _index
    )
        external
        view
        checkStrategyExistence(_id)
        returns (UserInfoEpoch memory userEpochStruct)
    {
        userEpochStruct = _userInfoEpoch[_id][_user][_index];
    }

    /**
     * @dev Fetches the guarantee parameters for an user for a certain index.
     * @param _id The _id of the strategy to fetch the information for.
     * @param _user The address of the user to fetch the information for.
     * @param _index The index of the user guarantee lock to fetch the information for.
     * @return userGuarantee The UserInfoEpoch struct associated with the provided id, _user and _index.
     */
    function getGuaranteeInfo(
        uint _id,
        address _user,
        uint _index
    )
        external
        view
        checkStrategyExistence(_id)
        returns (GuaranteeInfo memory userGuarantee)
    {
        userGuarantee = _userGuaranteeLock[_id][_user][_index];
    }

    ////////////////// UPDATE //////////////////

    /**
     * @dev Updates the current epoch information for the specified strategy
     * @param _id The Strategy _id
     *
     * This function checks if the current epoch's duration has been met or exceeded.
     * If true, it initializes a new epoch with its starting time as the current block timestamp.
     * If false, no action is taken.
     *
     * Requirements:
     * - The strategy must be initialized.
     * - The current block timestamp must be equal to or greater than the start
     *   time of the current epoch plus the epoch's duration.
     */
    function updateEpoch(
        uint _id
    ) private checkEpochExistence(_id) {
        uint currentEpoch = getCurrentEpoch(_id);

        if (
            block.timestamp >=
            _epochInfo[_id][currentEpoch].epochStartTime +
                _epochInfo[_id][currentEpoch].duration
        ) {
            require(_epochInfo[_id][currentEpoch].VPS > 0, "ERR_V.37");

            _epochInfo[_id][_epochCounter[_id]] = EpochInfo({
                totDepositors: 0,
                totDepositedAssets: 0,
                totWithdrawnShares: 0,
                VPS: 0,
                newShares: 0,
                currentWithdrawAssets: 0,
                epochStartTime: vaultGetter.getCurrentPeriod(_id),
                lastDepositorProcessed: 0,
                duration: _strategyInfo[_id].epochDuration
            });

            _epochCounter[_id]++;
        }
    }

    /// @notice Calculate fees to the treasury address and save it in the strategy mapping and returns adjusted VPS
    /**
     * @dev Internal function
     */
    /// @param _id Strategy _id
    /// @param _newVPS new Net Asset Value
    /// @return adjustedVPS The new VPS after fees have been deducted
    function takePerformanceFees(
        uint _id,
        uint _newVPS
    ) private returns (uint adjustedVPS, uint actualFee) {
        StrategyInfo storage strategy = _strategyInfo[_id];

        uint sharesMultiplier = 10 ** strategy.fundRepresentToken.decimals();
        uint totalSupplyShares = strategy.fundRepresentToken.totalSupply();
        actualFee = 0;
        adjustedVPS = _newVPS;

        if (strategy.watermark < _newVPS) {
            actualFee =
                ((_newVPS - strategy.watermark) *
                    strategy.fee *
                    totalSupplyShares) /
                feeBase /
                sharesMultiplier;
            if (actualFee > 0) {
                strategy.watermark = _newVPS;
                strategy.pendingFees += actualFee;

                // Calculate adjusted VPS based on the actual fee
                uint adjustedTotalValue = (_newVPS * totalSupplyShares) /
                    sharesMultiplier -
                    actualFee;
                adjustedVPS =
                    (adjustedTotalValue * sharesMultiplier) 
                    / totalSupplyShares;
            }
        }
    }

    /**
     * @dev Processes the fund associated with a particular strategy, handling deposits,
     * minting, and burning of shares.
     * @param _id The Strategy _id
     * @param _newVPS New value per share (VPS) expressed in decimals (same as assetToken)
     * - must be greater than 0
     *
     * This function performs the following actions:
     * 1. Retrieves the current epoch and strategy info, as well as adjusted VPS and performance Fees;
     * 2. Calculate the new shares and current withdrawal based on new VPS;
     * 3. Mints or burns shares depending on the new shares and total withdrawals.
     * 4. Handles deposits, withdrawals and performance fees by transferring the Asset tokens.
     *
     * Requirements:
     * - `_newVPS` must be greater than 0.
     * - The necessary amount of Asset tokens must be present in the contract for deposits if required.
     * - The necessary amount of Asset tokens must be present in the investAddress for withdrawals if required.
     */
    function processFund(uint _id, uint _newVPS) private {
        require(_newVPS > 0, "ERR_V.35");

        uint performanceFees;
        (_newVPS, performanceFees) = takePerformanceFees(_id, _newVPS);

        // Step 1
        EpochInfo storage epoch = _epochInfo[_id][
            _strategyInfo[_id].lastProcessedEpoch
        ];
        StrategyInfo memory strategy = _strategyInfo[_id];

        uint sharesMultiplier = 10 ** strategy.fundRepresentToken.decimals();

        // Step 2
        uint newShares = (epoch.totDepositedAssets * sharesMultiplier) /
            _newVPS;
        uint currentWithdrawAssets = (_newVPS * epoch.totWithdrawnShares) /
            sharesMultiplier;

        epoch.newShares = newShares;
        epoch.currentWithdrawAssets = currentWithdrawAssets;

        // Step 3
        if (newShares > epoch.totWithdrawnShares) {
            uint sharesToMint = newShares - epoch.totWithdrawnShares;
            bool success = strategy.fundRepresentToken.mint(sharesToMint);
            require(success, "ERR_V.8");
        } else {
            uint offSetShares = epoch.totWithdrawnShares - newShares;
            if (offSetShares > 0) {
                bool success = strategy.fundRepresentToken.burn(offSetShares);
                require(success, "ERR_V.4");
            }
        }

        // Step 4
        if (epoch.totDepositedAssets >= currentWithdrawAssets + performanceFees) {
            uint netDeposits = epoch.totDepositedAssets - currentWithdrawAssets - performanceFees;
            if (netDeposits > 0) {
                require(
                    strategy.assetToken.balanceOf(address(this)) >= netDeposits,
                    "ERR_V.12"
                );
                strategy.assetToken.safeTransfer(
                    strategy.investAddress,
                    netDeposits
                );
                emit Deposit(
                    address(this),
                    strategy.investAddress,
                    _id,
                    netDeposits
                );
            }
        } else {
            uint offSet = currentWithdrawAssets + performanceFees - epoch.totDepositedAssets;
            require(
                strategy.assetToken.balanceOf(strategy.investAddress) >= offSet,
                "ERR_V.13"
            );
            strategy.assetToken.safeTransferFrom(
                strategy.investAddress,
                address(this),
                offSet
            );
        }

        updateEpoch(_id);
    }

    /// @notice Sets new VPS of the strategy.
    /**
     * @dev Only Owner can call this function.
     *      Owner must transfer fund to our vault before calling this function
     */
    /// @param _id Strategy _id
    /// @param _newVPS New VPS value
    function rebalancing(
        uint _id,
        uint _newVPS
    ) external nonReentrant onlyOwner checkStrategyExistence(_id) {
        StrategyInfo storage strategy = _strategyInfo[_id];
        require(strategy.investAddress != address(0), "ERR_V.14");

        if (strategy.lastProcessedEpoch == 0) {
            EpochInfo storage initEpoch = _epochInfo[_id][0];
            if (initEpoch.VPS > 0) {
                require(
                    initEpoch.lastDepositorProcessed == initEpoch.totDepositors,
                    "ERR_V.16"
                );
                require(_epochCounter[_id] > 1, "ERR_V.17");
                strategy.lastProcessedEpoch++;
                EpochInfo storage newEpoch = _epochInfo[_id][1];
                require(
                    block.timestamp >=
                        newEpoch.epochStartTime + newEpoch.duration,
                    "ERR_V.18"
                );
                newEpoch.VPS = _newVPS;
            } else {
                require(
                    block.timestamp >=
                        initEpoch.epochStartTime + initEpoch.duration,
                    "ERR_V.18"
                );
                strategy.watermark = _newVPS;
                initEpoch.VPS = _newVPS;
            }
        } else {
            require(
                _epochInfo[_id][strategy.lastProcessedEpoch]
                    .lastDepositorProcessed ==
                    _epochInfo[_id][strategy.lastProcessedEpoch].totDepositors,
                "ERR_V.16"
            );
            strategy.lastProcessedEpoch++;
            require(
                _epochCounter[_id] > strategy.lastProcessedEpoch,
                "ERR_V.17"
            );
            EpochInfo storage subsequentEpoch = _epochInfo[_id][
                strategy.lastProcessedEpoch
            ];
            require(
                block.timestamp >=
                    subsequentEpoch.epochStartTime + subsequentEpoch.duration,
                "ERR_V.18"
            );
            subsequentEpoch.VPS = _newVPS;
        }

        processFund(_id, _newVPS);

        emit UpdateVPS(_id, strategy.lastProcessedEpoch, _newVPS);
    }

    ////////////////// MAIN //////////////////

    /// @notice Claim withdrawed token epochs
    /// @param _id Strategy _id
    function claimGuaranteeToken(
        uint _id
    )
        external
        nonReentrant
        checkStrategyExistence(_id)
        checkEpochExistence(_id)
    {
        StrategyInfo memory strategy = _strategyInfo[_id];
        UserInfo storage user = _userInfo[_id][_msgSender()];

        uint endIndex = user.numberOfLocks;
        uint startingIndexFinal = user.startingIndexGuarantee;
        uint actualGuarantee;
        for (uint i = user.startingIndexGuarantee; i < endIndex; i++) {
            if (
                block.timestamp <
                _userGuaranteeLock[_id][_msgSender()][i].lockStartTime +
                    strategy.lockPeriod
            ) {
                break;
            }
            actualGuarantee += _userGuaranteeLock[_id][_msgSender()][i]
                .lockAmount;
            startingIndexFinal = i + 1;
        }
        require(actualGuarantee > 0, "ERR_V.19");
        user.startingIndexGuarantee = startingIndexFinal;
        strategy.guaranteeToken.safeTransfer(_msgSender(), actualGuarantee);
        emit ClaimGuarantee(_id, _msgSender(), actualGuarantee);
    }

    /// @notice Users Deposit tokens to our vault
    /**
     * @dev Anyone can call this function if strategy is not paused.
     *      Users must approve deposit token before calling this function
     *      We mint represent token to users so that we can calculate each users deposit amount outside
     */
    /// @param _id Strategy _id
    /// @param _amount Token Amount to deposit
    function deposit(
        uint _id,
        uint _amount
    ) external nonReentrant checkStrategyExistence(_id) {
        require(_strategyInfo[_id].paused == false, "ERR_V.2");
        StrategyInfo storage strategy = _strategyInfo[_id];
        require(_amount > strategy.minDeposit, "ERR_V.20");
        require(
            strategy.assetToken.balanceOf(_msgSender()) >= _amount,
            "ERR_V.21"
        );
        uint curEpoch = getCurrentEpoch(_id);
        EpochInfo storage epoch = _epochInfo[_id][curEpoch];
        require (block.timestamp <=
            epoch.epochStartTime + epoch.duration, "ERR_V.37"
        );
        UserInfoEpoch storage userEpoch = _userInfoEpoch[_id][_msgSender()][
            curEpoch
        ];
        UserInfo storage user = _userInfo[_id][_msgSender()];

        require(
            epoch.totDepositedAssets + _amount <= strategy.maxDeposit,
            "ERR_V.23"
        );

        // Transfer guarantee token to the vault.
        vaultGetter.updateAll(_id);
        uint guaranteeAmount = (vaultGetter.getPrice(_id, _amount) *
            strategy.guaranteeFee) / feeBase;
        strategy.guaranteeToken.safeTransferFrom(
            _msgSender(),
            address(this),
            guaranteeAmount
        );

        GuaranteeInfo storage guaranteeInfo = _userGuaranteeLock[_id][
            _msgSender()
        ][user.numberOfLocks];
        if (userEpoch.epochGuaranteeIndex == 0)
            userEpoch.epochGuaranteeIndex = user.numberOfLocks;
        user.numberOfLocks++;
        guaranteeInfo.lockStartTime = block.timestamp;
        guaranteeInfo.lockAmount = guaranteeAmount;

        if (!userEpoch.hasDeposited) {
            require(epoch.totDepositors + 1 <= strategy.maxUsers, "ERR_V.22");
            _depositors[_id][curEpoch][epoch.totDepositors] = _msgSender();
            userEpoch.depositIndex = epoch.totDepositors;
            epoch.totDepositors++;
            userEpoch.hasDeposited = true;
        }

        epoch.totDepositedAssets += _amount;
        strategy.assetToken.safeTransferFrom(
            _msgSender(),
            address(this),
            _amount
        );
        userEpoch.depositInfo += _amount;
        emit Deposit(_msgSender(), address(this), _id, _amount);
    }

    /// @notice Immediately withdraw current pending deposit amount
    /// @param _id Strategy _id
    function cancelDeposit(
        uint _id
    )
        external
        nonReentrant
        checkStrategyExistence(_id)
        checkEpochExistence(_id)
    {
        StrategyInfo storage strategy = _strategyInfo[_id];
        uint curEpoch = getCurrentEpoch(_id);
        EpochInfo storage epoch = _epochInfo[_id][curEpoch];
        require(
            block.timestamp < epoch.epochStartTime + epoch.duration,
            "ERR_V.24"
        );
        UserInfoEpoch storage userEpoch = _userInfoEpoch[_id][_msgSender()][
            curEpoch
        ];
        uint amount = userEpoch.depositInfo;
        require(amount > 0, "ERR_V.20");
        userEpoch.depositInfo = 0;
        epoch.totDepositedAssets -= amount;
        strategy.assetToken.safeTransfer(_msgSender(), amount);

        UserInfo storage user = _userInfo[_id][_msgSender()];
        // Guarantee refund logic start //
        uint actualGuarantee;
        uint iterations;
        for (
            uint i = userEpoch.epochGuaranteeIndex;
            i < user.numberOfLocks;
            i++
        ) {
            actualGuarantee += _userGuaranteeLock[_id][_msgSender()][i]
                .lockAmount;
            iterations++;
        }
        user.numberOfLocks -= iterations;
        strategy.guaranteeToken.safeTransfer(_msgSender(), actualGuarantee);
        // Guarantee refund logic end //
        if (_depositors[_id][curEpoch][epoch.totDepositors] == _depositors[_id][curEpoch][userEpoch.depositIndex]) {
            _depositors[_id][curEpoch][epoch.totDepositors] = address(0);
        } else {
            address replaceAddress = _depositors[_id][curEpoch][epoch.totDepositors];
            _depositors[_id][curEpoch][epoch.totDepositors] = address(0);
            _depositors[_id][curEpoch][userEpoch.depositIndex] = replaceAddress;
            _userInfoEpoch[_id][replaceAddress][curEpoch].depositIndex = userEpoch
            .depositIndex;
        }
        userEpoch.depositIndex = 0;
        epoch.totDepositors--;
        userEpoch.hasDeposited = false;

        emit CancelDeposit(_msgSender(), _id, amount);
    }

    /// @notice Sends Withdraw Request to vault
    /**
     * @dev Withdraw amount user shares from vault
     */
    /// @param _id Strategy _id
    function withdraw(
        uint _id,
        uint _amount
    )
        external
        nonReentrant
        checkStrategyExistence(_id)
        checkEpochExistence(_id)
    {
        uint sharesBalance = _strategyInfo[_id].fundRepresentToken.balanceOf(
            _msgSender()
        );
        require(sharesBalance >= _amount, "ERR_V.25");
        uint curEpoch = getCurrentEpoch(_id);
        require (block.timestamp <=
            _epochInfo[_id][curEpoch].epochStartTime + _epochInfo[_id][curEpoch].duration, "ERR_V.37"
        );
        UserInfoEpoch storage userEpoch = _userInfoEpoch[_id][_msgSender()][
            curEpoch
        ];
        UserInfo storage user = _userInfo[_id][_msgSender()];
        if (user.lastEpoch > 0 && userEpoch.withdrawInfo == 0)
            _claimWithdrawedTokens(_id, user.lastEpoch, _msgSender());

        _epochInfo[_id][curEpoch].totWithdrawnShares += _amount;
        userEpoch.withdrawInfo += _amount;
        if (user.lastEpoch != curEpoch) user.lastEpoch = curEpoch;
        _strategyInfo[_id].fundRepresentToken.safeTransferFrom(
            _msgSender(),
            address(this),
            _amount
        );
        emit Withdraw(_msgSender(), _id, _amount);
    }

    /// @notice Immediately withdraw current pending shares amount
    /// @param _id Strategy _id
    function cancelWithdraw(
        uint _id
    )
        external
        nonReentrant
        checkStrategyExistence(_id)
        checkEpochExistence(_id)
    {
        StrategyInfo storage strategy = _strategyInfo[_id];
        uint curEpoch = getCurrentEpoch(_id);
        EpochInfo storage epoch = _epochInfo[_id][curEpoch];
        require(
            block.timestamp < epoch.epochStartTime + epoch.duration,
            "ERR_V.24"
        );
        UserInfoEpoch storage userEpoch = _userInfoEpoch[_id][_msgSender()][
            curEpoch
        ];
        UserInfo storage user = _userInfo[_id][_msgSender()];
        uint amount = userEpoch.withdrawInfo;
        require(amount > 0, "ERR_V.20");
        userEpoch.withdrawInfo = 0;
        user.lastEpoch = 0;
        require(epoch.totWithdrawnShares >= amount, "ERR_V.26");
        epoch.totWithdrawnShares -= amount;
        strategy.fundRepresentToken.safeTransfer(_msgSender(), amount);

        emit CancelWithdraw(_msgSender(), _id, amount);
    }

    /// @notice Internal get withdraw tokens from vault for user
    /**
     * @dev Withdraw user funds from vault
     */
    /// @param _id Strategy _id
    /// @param _user Strategy _id
    function _claimWithdrawedTokens(
        uint _id,
        uint _lastEpoch,
        address _user
    ) internal {
        EpochInfo storage epoch = _epochInfo[_id][_lastEpoch];

        uint withdrawInfo = _userInfoEpoch[_id][_user][_lastEpoch].withdrawInfo;
        uint availableToClaim;
        if (withdrawInfo > 0) {
            uint dueWithdraw = (withdrawInfo * epoch.currentWithdrawAssets) /
                epoch.totWithdrawnShares;

            availableToClaim += dueWithdraw;
            emit ClaimWithdrawedToken(_id, _user, _lastEpoch, dueWithdraw);
        }
        if (availableToClaim > 0)
            _strategyInfo[_id].assetToken.safeTransfer(_user, availableToClaim);
        emit WithdrawedToken(_id, _user, availableToClaim);
    }

    /// @notice Get withdraw tokens from vault
    /**
     * @dev Withdraw my fund from vault
     */
    /// @param _id Strategy _id
    function claimWithdrawedTokens(
        uint _id
    ) external nonReentrant checkStrategyExistence(_id) {
        UserInfo storage user = _userInfo[_id][_msgSender()];
        uint lastEpoch = user.lastEpoch;
        require(lastEpoch > 0, "ERR_V.36");
        _claimWithdrawedTokens(_id, lastEpoch, _msgSender());
        user.lastEpoch = 0;
    }

    /// @notice Distribute shares to the epoch depositors
    /**
     * @dev Only Owner can call this function if deposit duration is passed.
     *      Owner must setPaused(false)
     */
    /// @param _id Strategy _id
    function processDeposits(
        uint _id
    ) external nonReentrant onlyOwner checkStrategyExistence(_id) {
        StrategyInfo memory strategy = _strategyInfo[_id];
        EpochInfo memory epoch = _epochInfo[_id][strategy.lastProcessedEpoch];
        require(epoch.VPS > 0, "ERR_V.27");
        require(epoch.lastDepositorProcessed == 0, "ERR_V.28");
        if (epoch.totDepositedAssets == 0) {
            return;
        }

        distributeShares(_id);
    }

    /**
     * @dev Continues the process of distributing shares for a specific strategy, if possible.
     * This function is only callable by the contract owner.
     * @param _id The _id of the strategy for which to continue distributing shares.
     */
    function continueDistributingShares(
        uint _id
    ) external nonReentrant onlyOwner checkStrategyExistence(_id) {
        // Check if there's anything to distribute
        EpochInfo memory epoch = _epochInfo[_id][
            _strategyInfo[_id].lastProcessedEpoch
        ];
        require(epoch.VPS > 0, "ERR_V.27");
        require(epoch.lastDepositorProcessed != 0, "ERR_V.29");
        require(epoch.lastDepositorProcessed < epoch.totDepositors, "ERR_V.30");
        distributeShares(_id);
    }

    /**
     * @dev Distributes the newly minted shares among the depositors of a specific strategy.
     * The function processes depositors until it runs out of gas.
     * @param _id The _id of the strategy for which to distribute shares.
     */
    function distributeShares(uint _id) internal {
        EpochInfo storage epoch = _epochInfo[_id][
            _strategyInfo[_id].lastProcessedEpoch
        ];
        uint i = epoch.lastDepositorProcessed;
        uint sharesToDistribute = epoch.newShares;

        while (i < epoch.totDepositors && gasleft() > gasBuffer) {
            address investor = _depositors[_id][_strategyInfo[_id].lastProcessedEpoch][i];
            uint depositInfo = _userInfoEpoch[_id][investor][
                _strategyInfo[_id].lastProcessedEpoch
            ].depositInfo;
            uint dueShares = (sharesToDistribute * depositInfo) /
                epoch.totDepositedAssets;

            if (dueShares > 0) {
                // Transfer the shares
                _strategyInfo[_id].fundRepresentToken.safeTransfer(
                    investor,
                    dueShares
                );
            }

            i++;
        }

        epoch.lastDepositorProcessed = i;
    }

    /**
     * @notice Distribute pending fees to the treasury addresses
     * @dev Internal function
     */
    /// @param _id Strategy _id
    function sendPendingFees(
        uint _id
    ) external nonReentrant onlyOwner checkStrategyExistence(_id) {
        StrategyInfo storage strategy = _strategyInfo[_id];

        require(
            block.timestamp >=
                strategy.lastFeeDistribution + strategy.feeDuration,
            "ERR_V.31"
        );
        strategy.lastFeeDistribution = block.timestamp;

        uint pendingFees = strategy.pendingFees;
        require(pendingFees > 0, "ERR_V.35");
        require(
            strategy.assetToken.balanceOf(address(this)) >= pendingFees,
            "ERR_V.32"
        );
        strategy.pendingFees = 0;

        address addr0 = strategy.withdrawAddress[0];
        address addr1 = strategy.withdrawAddress[1];
        emit SendFeeWithOwner(_id, addr0, pendingFees / 2);
        emit SendFeeWithOwner(_id, addr1, pendingFees / 2);
        strategy.assetToken.safeTransfer(addr0, pendingFees / 2);
        strategy.assetToken.safeTransfer(addr1, pendingFees / 2);
    }

    /// @notice Withdraw ERC-20 Token to the owner
    /**
     * @dev Only Owner can call this function
     */
    /// @param _tokenContract ERC-20 Token address
    function withdrawERC20(IERC20 _tokenContract) external onlyOwner {
        for (uint i = 0; i < strategiesCounter; i++) {
            require(
                _strategyInfo[i].guaranteeToken != _tokenContract,
                "ERR_V.34"
            );
            require(_strategyInfo[i].assetToken != _tokenContract, "ERR_V.34");
        }
        _tokenContract.safeTransfer(
            _msgSender(),
            _tokenContract.balanceOf(address(this))
        );
    }
}

// File: contracts/CIV-VaultFactory.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

/// @custom:security-contact info@civfund.org
contract CIVFundShare is ERC20, Ownable {
    constructor(address _owner) ERC20("CIVFundShare", "XCIV") {
        _transferOwnership(_owner);
    }

    function mint(uint _amount) public onlyOwner returns (bool) {
        _mint(_msgSender(), _amount);
        return true;
    }

    function burn(uint _amount) public returns (bool) {
        _burn(_msgSender(), _amount);
        return true;
    }
}

contract CIVFundShareFactory {
    function createCIVFundShare() public returns (CIVFundShare) {
        CIVFundShare fundRepresentToken = new CIVFundShare(msg.sender);
        return fundRepresentToken;
    }
}

// File: contracts/CIV-VaultGetter.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "./dependencies/FixedPoint.sol";
import "./interfaces/ICivFund.sol";
import "./dependencies/UniswapV2OracleLibrary.sol";
import "./CIV-TimeOracle.sol";

////////////////// ERROR CODES //////////////////
/*
    ERR_VG.1 = "Msg.sender is not the Vault";
    ERR_VG.2 = "Can't get first pair";
    ERR_VG.3 = "Can't get second pair";
    ERR_VG.4 = "Epoch not yet expired";
    ERR_VG.5 = "Nothing to withdraw";
    ERR_VG.6 = "Wait for the previos epoch to settle before requesting withdraw";
*/

contract CivVaultGetter is ReentrancyGuard {
    using SafeMath for uint;
    using FixedPoint for *;

    ICivVault public civVault;
    /// @notice Uniswap Factory address
    address public constant UNISWAP_FACTORY =
        0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; // to be adjusted for mainnet
    /// @notice Wrapped ETH Address
    address public constant WETH_ADDRESS =
        0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // to be adjusted for mainnet
    /// @notice Dead Address
    address public constant NULL_ADDRESS =
        0x0000000000000000000000000000000000000000;
    /// @notice Uniswap TWAP Period
    uint public constant PERIOD = 24 hours;

    /// @notice Each Strategy Uniswap Pair Info List
    mapping(uint => PairInfo[]) public pairInfo;

    /// @notice Each Strategy time Oracle
    mapping(uint => TimeOracle) public timeOracle;

    modifier onlyVault() {
        require(msg.sender == address(civVault), "ERR_VG.1");
        _;
    }

    constructor(address _civVaultAddress) {
        civVault = ICivVault(_civVaultAddress);
    }

    /// @notice Add new uniswap pair info to pairInfo list
    /// @dev Interal function
    /// @param _id Strategy Id
    /// @param _pair Uniswap Pair Interface
    function addPair(uint _id, IUniswapV2Pair _pair) internal {
        (, , uint32 blockTimestampLast) = _pair.getReserves();
        (
            uint price0Cumulative,
            uint price1Cumulative,
            uint32 blockTimestamp
        ) = UniswapV2OracleLibrary.currentCumulativePrices(address(_pair));
        uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
        FixedPoint.uq112x112 memory price0Average = FixedPoint.uq112x112(
            uint224(
                (price0Cumulative - _pair.price0CumulativeLast()) / timeElapsed
            )
        );
        FixedPoint.uq112x112 memory price1Average = FixedPoint.uq112x112(
            uint224(
                (price1Cumulative - _pair.price1CumulativeLast()) / timeElapsed
            )
        );
        pairInfo[_id].push(
            PairInfo({
                pair: _pair,
                price0CumulativeLast: price0Cumulative,
                price1CumulativeLast: price1Cumulative,
                token0: _pair.token0(),
                token1: _pair.token1(),
                price0Average: price0Average,
                price1Average: price1Average,
                blockTimestampLast: blockTimestamp
            })
        );
    }

    /// @notice Deploy new Time Oracle for the strategy
    /// @param _id Strategy Id
    /// @param _epochDuration Epoch Duration
    function addTimeOracle(uint _id, uint _epochDuration) external onlyVault {
        timeOracle[_id] = new TimeOracle(_epochDuration);
    }

    /// @notice Add new uniswap pair info to pairInfo list from token pair address
    /// @param _id Strategy Id
    /// @param _token0 Token0 Address
    /// @param _token1 Token1 Address
    function addUniPair(
        uint _id,
        address _token0,
        address _token1
    ) external nonReentrant onlyVault {
        IUniswapV2Factory factory = IUniswapV2Factory(UNISWAP_FACTORY);
        address pairAddress = factory.getPair(_token1, _token0);

        if (pairAddress == NULL_ADDRESS) {
            pairAddress = factory.getPair(_token1, WETH_ADDRESS);
            require(pairAddress != NULL_ADDRESS, "ERR_VG.2");
            IUniswapV2Pair _pairA = IUniswapV2Pair(pairAddress);
            addPair(_id, _pairA);
            pairAddress = factory.getPair(_token0, WETH_ADDRESS);
            require(pairAddress != NULL_ADDRESS, "ERR_VG.3");
            IUniswapV2Pair _pairB = IUniswapV2Pair(pairAddress);
            addPair(_id, _pairB);
        } else {
            IUniswapV2Pair _pair = IUniswapV2Pair(pairAddress);
            addPair(_id, _pair);
        }
    }

    /// @notice Update Uniswap LP token price
    /// @dev Anyone can call this function but we update price after PERIOD of time
    /// @param _id Strategy Id
    /**
     * @param _index PairInfo index
     *              We can have 1 or 2 index
     *              If Deposit/Guarantee Token Pair exists on uniswap there's only 1 pairInfo
     *              If Deposit/Guarantee Token Pair does not exist on uniswap, we have 2 pairInfo
     *              Deposit/WETH Pair and Guarantee/WETH token pair to get price
     */
    function update(uint _id, uint _index) public {
        PairInfo storage info = pairInfo[_id][_index];
        (
            uint price0Cumulative,
            uint price1Cumulative,
            uint32 blockTimestamp
        ) = UniswapV2OracleLibrary.currentCumulativePrices(address(info.pair));
        uint32 timeElapsed = blockTimestamp - info.blockTimestampLast; // overflow is desired

        // ensure that at least one full period has passed since the last update
        if (timeElapsed < PERIOD) return;

        // overflow is desired, casting never truncates
        // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
        info.price0Average = FixedPoint.uq112x112(
            uint224(
                (price0Cumulative - info.price0CumulativeLast) / timeElapsed
            )
        );
        info.price0CumulativeLast = price0Cumulative;
        info.price1Average = FixedPoint.uq112x112(
            uint224(
                (price1Cumulative - info.price1CumulativeLast) / timeElapsed
            )
        );
        info.price1CumulativeLast = price1Cumulative;
        info.blockTimestampLast = blockTimestamp;
    }

    /// @notice Update Uniswap LP token price for all pairs
    /// @dev Anyone can call this function but we update price after PERIOD of time
    /// @param _id Strategy Id
    function updateAll(uint _id) public {
        for (uint i = 0; i < pairInfo[_id].length; i++) update(_id, i);
    }

    /// @notice Set new epochDuration for Strategy
    /// @dev Only the Getter can call this function from timeOracle
    /// @param _id Strategy Id
    /// @param _newEpochDuration new epochDuration
    function setEpochDuration(uint _id, uint _newEpochDuration) public {
        timeOracle[_id].setEpochDuration(_newEpochDuration);
    }

    /**
     * @dev Get the current period for a Strategy
     * @param _id The ID of the Strategy
     * @return currentPeriodStartTime The end time for the current period
     */
    function getCurrentPeriod(
        uint _id
    ) external view returns (uint currentPeriodStartTime) {
        return timeOracle[_id].getCurrentPeriod();
    }

    /// @dev Get Guarantee amount for deposit to the vault
    /// @param _id Strategy Id
    /// @param _amount Amount to deposit in the vault
    /// @return amount Guarantee Token Amount needs for deposit in a given strategy
    function getDepositGuarantee(
        uint _id,
        uint _amount
    ) external view returns (uint) {
        return
            (getPrice(_id, _amount) *
                civVault.getStrategyInfo(_id).guaranteeFee) /
            civVault.feeBase();
    }

    /// @dev Get available deposit amount based of user's guarantee amount
    /// @param _id Strategy Id
    /// @param _user User address
    /// @return amount Current Available Deposit amount regarding users's current guarantee token balance in a given strategy
    function getAllowedDeposit(
        uint _id,
        address _user
    ) external view returns (uint) {
        IERC20Extended guarantee = IERC20Extended(
            address(civVault.getStrategyInfo(_id).guaranteeToken)
        );
        return
            (getReversePrice(_id, guarantee.balanceOf(_user)) *
                civVault.feeBase()) /
            civVault.getStrategyInfo(_id).guaranteeFee;
    }

    /// @dev Get Guarantee Token symbol and decimal
    /// @param _id Strategy Id
    /// @return symbol Guarantee Token Symbol in a given strategy
    /// @return decimals Guarantee Token Decimal in a given strategy
    function getGuaranteeTokenInfo(
        uint _id
    ) external view returns (string memory symbol, uint decimals) {
        IERC20Extended guarantee = IERC20Extended(
            address(civVault.getStrategyInfo(_id).guaranteeToken)
        );
        symbol = guarantee.symbol();
        decimals = guarantee.decimals();
    }

    /// @dev Get claimable guarantee token amount
    /// @param _id Strategy Id
    /// @param _user userAddress
    /// @return amount Current claimable guarantee token amount
    function getClaimableGuaranteeToken(
        uint _id,
        address _user
    ) external view returns (uint) {
        StrategyInfo memory strategy = civVault.getStrategyInfo(_id);
        UserInfo memory user = civVault.getUserInfo(_id, _user);
        uint endIndex = user.numberOfLocks;
        uint unLocked;
        for (uint i = user.startingIndexGuarantee; i < endIndex; i++) {
            if (
                block.timestamp <
                civVault.getGuaranteeInfo(_id, _user, i).lockStartTime +
                    strategy.lockPeriod
            ) {
                break;
            }
            unLocked += civVault.getGuaranteeInfo(_id, _user, i).lockAmount;
        }

        return unLocked;
    }

    /**
     * @dev Retrieves the current balance of the user's guarantee token, fund representative token, and liquidity strategy token in a specific strategy.
     * @param _id The ID of the strategy from which to retrieve user balance information.
     * @param _user The user EOA
     * @return guaranteeBalance The balance of the user's guarantee token in the given strategy.
     * @return representTokenBalance The balance of the user's fund representative token in the given strategy.
     * @return assetTokenBalance The balance of the user's liquidity strategy token in the given strategy.
     * @return guaranteeAddress The contract address of the guarantee token in the given strategy.
     * @return representTokenAddress The contract address of the fund representative token in the given strategy.
     * @return assetTokenAddress The contract address of the liquidity strategy token in the given strategy.
     */
    function getUserBalances(
        uint _id,
        address _user
    )
        external
        view
        returns (
            uint guaranteeBalance,
            uint representTokenBalance,
            uint assetTokenBalance,
            address guaranteeAddress,
            address representTokenAddress,
            address assetTokenAddress
        )
    {
        guaranteeAddress = address(
            civVault.getStrategyInfo(_id).guaranteeToken
        );
        IERC20 guarantee = IERC20(guaranteeAddress);
        guaranteeBalance = guarantee.balanceOf(_user);

        representTokenAddress = address(
            civVault.getStrategyInfo(_id).fundRepresentToken
        );
        IERC20 representToken = IERC20(representTokenAddress);
        representTokenBalance = representToken.balanceOf(_user);

        assetTokenAddress = address(civVault.getStrategyInfo(_id).assetToken);
        IERC20 assetToken = IERC20(assetTokenAddress);
        assetTokenBalance = assetToken.balanceOf(_user);

        return (
            guaranteeBalance,
            representTokenBalance,
            assetTokenBalance,
            guaranteeAddress,
            representTokenAddress,
            assetTokenAddress
        );
    }

    /// @notice get net values for new VPS for a certain epoch
    /// @param _id Strategy Id
    /// @param _newVPS New Value Per Share
    /// @param _epochId Epoch Id
    /// @return _epochs array of unclaimed epochs
    function getNetValues(
        uint _id,
        uint _newVPS,
        uint _epochId
    ) public view returns (uint, uint) {
        EpochInfo memory epoch = civVault.getEpochInfo(_id, _epochId);
        StrategyInfo memory strategy = civVault.getStrategyInfo(_id);
        require(
            block.timestamp >=
                epoch.epochStartTime +
                    epoch.duration,
            "ERR_VG.4"
        );
        uint currentWithdrawAssets = _newVPS * epoch.totWithdrawnShares;
        uint decimals = uint(strategy.fundRepresentToken.decimals());
        uint multiplier = 10 ** decimals;
        uint newShares = (epoch.totDepositedAssets * multiplier) / _newVPS;

        return (currentWithdrawAssets, newShares);
    }

    /// @notice get unclaimed withdrawed token epochs
    /// @param _id Strategy Id
    /// @return _epochs array of unclaimed epochs
    function getUnclaimedTokens(
        uint _id,
        address _user
    ) public view returns (uint) {
        uint lastEpoch = civVault.getUserInfo(_id, _user).lastEpoch;
        require(lastEpoch > 0, "ERR_VG.5");
        EpochInfo memory epoch = civVault.getEpochInfo(_id, lastEpoch);
        require(epoch.VPS > 0, "ERR_VG.6");
        uint withdrawInfo = civVault
            .getUserInfoEpoch(_id, _user, lastEpoch)
            .withdrawInfo;

        return
            (withdrawInfo * epoch.currentWithdrawAssets) /
            epoch.totWithdrawnShares;
    }

    /// @notice Get Price of the each strategy's guarantee token amount based on deposit token amount
    /// @dev Public Function
    /// @param _id Strategy Id
    /// @param _amountIn deposit token amount
    /// @return amountOut Price of the token1 in a given strategy
    function getPrice(
        uint _id,
        uint _amountIn
    ) public view virtual returns (uint amountOut) {
        StrategyInfo memory strategyInfo = civVault.getStrategyInfo(_id);
        PairInfo[] memory curPairInfo = pairInfo[_id];
        if (curPairInfo.length == 1) {
            if (address(strategyInfo.assetToken) == curPairInfo[0].token0)
                amountOut = curPairInfo[0]
                    .price0Average
                    .mul(_amountIn)
                    .decode144();
            else
                amountOut = curPairInfo[0]
                    .price1Average
                    .mul(_amountIn)
                    .decode144();
        } else {
            FixedPoint.uq112x112 memory value;
            if (address(strategyInfo.guaranteeToken) == curPairInfo[0].token0) {
                value = curPairInfo[0].price1Average;
            } else {
                value = curPairInfo[0].price0Average;
            }
            if (address(strategyInfo.assetToken) == curPairInfo[1].token0) {
                value = value.muluq(curPairInfo[1].price1Average.reciprocal());
            } else {
                value = value.muluq(curPairInfo[1].price0Average.reciprocal());
            }
            amountOut = value.mul(_amountIn).decode144();
        }
    }

    /// @notice Get Price of the each strategy's deposit token amount based on guarantee token amount
    /// @dev Public Function
    /// @param _id Strategy Id
    /// @param _amountIn guarantee token amount
    /// @return amountOut Price of the token0 in a given strategy
    function getReversePrice(
        uint _id,
        uint _amountIn
    ) public view virtual returns (uint amountOut) {
        StrategyInfo memory strategyInfo = civVault.getStrategyInfo(_id);
        PairInfo[] memory curPairInfo = pairInfo[_id];
        if (curPairInfo.length == 1) {
            if (address(strategyInfo.guaranteeToken) == curPairInfo[0].token0)
                amountOut = curPairInfo[0]
                    .price0Average
                    .mul(_amountIn)
                    .decode144();
            else
                amountOut = curPairInfo[0]
                    .price1Average
                    .mul(_amountIn)
                    .decode144();
        } else {
            FixedPoint.uq112x112 memory value;
            if (address(strategyInfo.assetToken) == curPairInfo[0].token0) {
                value = curPairInfo[0].price1Average;
            } else {
                value = curPairInfo[0].price0Average;
            }
            if (address(strategyInfo.guaranteeToken) == curPairInfo[1].token0) {
                value = value.muluq(curPairInfo[1].price1Average.reciprocal());
            } else {
                value = value.muluq(curPairInfo[1].price0Average.reciprocal());
            }
            amountOut = value.mul(_amountIn).decode144();
        }
    }
}

// File: contracts/dependencies/FixedPoint.sol



// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;

import "./FullMath.sol";

// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
    // range: [0, 2**112 - 1]
    // resolution: 1 / 2**112
    struct uq112x112 {
        uint224 _x;
    }

    // range: [0, 2**144 - 1]
    // resolution: 1 / 2**112
    struct uq144x112 {
        uint256 _x;
    }

    uint8 public constant RESOLUTION = 112;
    uint256 public constant Q112 = 0x10000000000000000000000000000; // 2**112
    uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; // 2**224
    uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits)

    // encode a uint112 as a UQ112x112
    function encode(uint112 x) internal pure returns (uq112x112 memory) {
        return uq112x112(uint224(x) << RESOLUTION);
    }

    // encodes a uint144 as a UQ144x112
    function encode144(uint144 x) internal pure returns (uq144x112 memory) {
        return uq144x112(uint256(x) << RESOLUTION);
    }

    // decode a UQ112x112 into a uint112 by truncating after the radix point
    function decode(uq112x112 memory self) internal pure returns (uint112) {
        return uint112(self._x >> RESOLUTION);
    }

    // decode a UQ144x112 into a uint144 by truncating after the radix point
    function decode144(uq144x112 memory self) internal pure returns (uint144) {
        return uint144(self._x >> RESOLUTION);
    }

    // multiply a UQ112x112 by a uint, returning a UQ144x112
    // reverts on overflow
    function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) {
        uint256 z = 0;
        require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint::mul: overflow');
        return uq144x112(z);
    }

    // multiply a UQ112x112 by an int and decode, returning an int
    // reverts on overflow
    function muli(uq112x112 memory self, int256 y) internal pure returns (int256) {
        uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112);
        require(z < 2**255, 'FixedPoint::muli: overflow');
        return y < 0 ? -int256(z) : int256(z);
    }

    // multiply a UQ112x112 by a UQ112x112, returning a UQ112x112
    // lossy
    function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) {
        if (self._x == 0 || other._x == 0) {
            return uq112x112(0);
        }
        uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0
        uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112
        uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0
        uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112

        // partial products
        uint224 upper = uint224(upper_self) * upper_other; // * 2^0
        uint224 lower = uint224(lower_self) * lower_other; // * 2^-224
        uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112
        uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112

        // so the bit shift does not overflow
        require(upper <= type(uint112).max, 'FixedPoint::muluq: upper overflow');

        // this cannot exceed 256 bits, all values are 224 bits
        uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION);

        // so the cast does not overflow
        require(sum <= type(uint224).max, 'FixedPoint::muluq: sum overflow');

        return uq112x112(uint224(sum));
    }

    // returns a UQ112x112 which represents the ratio of the numerator to the denominator
    // can be lossy
    function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
        require(denominator > 0, 'FixedPoint::fraction: division by zero');
        if (numerator == 0) return FixedPoint.uq112x112(0);

        if (numerator <= type(uint144).max) {
            uint256 result = (numerator << RESOLUTION) / denominator;
            require(result <= type(uint224).max, 'FixedPoint::fraction: overflow');
            return uq112x112(uint224(result));
        } else {
            uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
            require(result <= type(uint224).max, 'FixedPoint::fraction: overflow');
            return uq112x112(uint224(result));
        }
    }

    // take the reciprocal of a UQ112x112
    // reverts on overflow
    // lossy
    function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
        require(self._x != 0, 'FixedPoint::reciprocal: reciprocal of zero');
        require(self._x != 1, 'FixedPoint::reciprocal: overflow');
        return uq112x112(uint224(Q224 / self._x));
    }
}

// File: contracts/dependencies/FullMath.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(
        uint256 a,
        uint256 b,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        // 512-bit multiply [prod1 prod0] = a * b
        // Compute the product mod 2**256 and mod 2**256 - 1
        // then 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; // Least significant 256 bits of the product
        uint256 prod1; // Most significant 256 bits of the product
        assembly {
            let mm := mulmod(a, b, not(0))
            prod0 := mul(a, b)
            prod1 := sub(sub(mm, prod0), lt(mm, prod0))
        }

        // Handle non-overflow cases, 256 by 256 division
        if (prod1 == 0) {
            require(denominator > 0);
            assembly {
                result := div(prod0, denominator)
            }
            return result;
        }

        // Make sure the result is less than 2**256.
        // Also prevents denominator == 0
        require(denominator > prod1);

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

        // Make division exact by subtracting the remainder from [prod1 prod0]
        // Compute remainder using mulmod
        uint256 remainder;
        assembly {
            remainder := mulmod(a, b, denominator)
        }
        // Subtract 256 bit number from 512 bit number
        assembly {
            prod1 := sub(prod1, gt(remainder, prod0))
            prod0 := sub(prod0, remainder)
        }

        // Factor powers of two out of denominator
        // Compute largest power of two divisor of denominator.
        // Always >= 1.
        //uint256 twos = -denominator & denominator;
        uint256 twos = denominator & (~denominator + 1);
        // Divide denominator by power of two
        assembly {
            denominator := div(denominator, twos)
        }

        // Divide [prod1 prod0] by the factors of two
        assembly {
            prod0 := div(prod0, twos)
        }
        // Shift in bits from prod1 into prod0. For this we need
        // to flip `twos` such that it is 2**256 / twos.
        // If twos is zero, then it becomes one
        assembly {
            twos := add(div(sub(0, twos), twos), 1)
        }
        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
        // correct for four bits. That is, denominator * inv = 1 mod 2**4
        uint256 inv = (3 * denominator) ^ 2;
        // Now use 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.
        inv *= 2 - denominator * inv; // inverse mod 2**8
        inv *= 2 - denominator * inv; // inverse mod 2**16
        inv *= 2 - denominator * inv; // inverse mod 2**32
        inv *= 2 - denominator * inv; // inverse mod 2**64
        inv *= 2 - denominator * inv; // inverse mod 2**128
        inv *= 2 - denominator * inv; // 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 precoditions 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 * inv;
        return result;
    }

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(
        uint256 a,
        uint256 b,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        result = mulDiv(a, b, denominator);
        if (mulmod(a, b, denominator) > 0) {
            require(result < type(uint256).max);
            result++;
        }
    }
}

// File: contracts/dependencies/UniswapV2OracleLibrary.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;

import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "./FixedPoint.sol";

// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
    using FixedPoint for *;

    // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
    function currentBlockTimestamp() internal view returns (uint32) {
        return uint32(block.timestamp % 2 ** 32);
    }

    // produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
    function currentCumulativePrices(
        address pair
    ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
        blockTimestamp = currentBlockTimestamp();
        price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
        price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();

        // if time has elapsed since the last update on the pair, mock the accumulated price values
        (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
        if (blockTimestampLast != blockTimestamp) {
            // subtraction overflow is desired
            uint32 timeElapsed = blockTimestamp - blockTimestampLast;
            // addition overflow is desired
            // counterfactual
            price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
            // counterfactual
            price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
        }
    }
}
// File: contracts/interfaces/ICivFund.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.18;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "../dependencies/FixedPoint.sol";

struct StrategyInfo {
    // Info on each strategy
    IERC20 assetToken; // Address of asset token e.g. USDT
    IERC20 guaranteeToken; // Guarantee Token address e.g. Stone
    ICivFundRT fundRepresentToken; // Fund Represent tokens for deposit in the strategy XCIV
    uint fee; // Strategy Fee Amount
    uint guaranteeFee; // Strategy Guarantee Fee Amount
    uint maxDeposit; // Strategy Max Deposit Amount per Epoch
    uint maxUsers; // Strategy Max User per Epoch
    uint minDeposit; // Strategy Min Deposit Amount
    uint epochDuration; // Duration of an Epoch
    uint lockPeriod; // Strategy Guarantee Token Lock Period
    uint feeDuration; // Fee withdraw period
    uint lastFeeDistribution; // Last timestamp of distribution
    uint lastProcessedEpoch; // Last Epoch Processed
    uint watermark; // Fee watermark
    uint pendingFees; // Pending fees that owner can withdraw
    address[] withdrawAddress; // Strategy Withdraw Address
    address investAddress; // Strategy Invest Address
    bool initialized; // Is strategy initialized?
    bool paused; // Flag that deposit is paused or not
}

struct EpochInfo {
    uint totDepositors; // Current depositors of the epoch
    uint totDepositedAssets; // Tot deposited asset in current epoch
    uint totWithdrawnShares; // Tot withdrawn asset in current epoch
    uint VPS; // VPS after rebalancing
    uint newShares; // New shares after rebalancing
    uint currentWithdrawAssets; // Withdrawn asset after rebalancing
    uint epochStartTime; // Epoch start time from time oracle
    uint lastDepositorProcessed; // Last depositor that has recived shares
    uint duration;
}

struct UserInfo {
    uint lastEpoch; // Last withdraw epoch
    uint startingIndexGuarantee; // Starting index of guarantee lock
    uint numberOfLocks; // Number of guarantee locks the user has
}

struct GuaranteeInfo {
    uint lockStartTime; // startTime of the guarantee lock
    uint lockAmount; // Amount of guarantee locked
}

struct UserInfoEpoch {
    uint depositInfo;
    uint withdrawInfo;
    uint depositIndex;
    uint epochGuaranteeIndex;
    bool hasDeposited;
}

struct AddStrategyParam {
    IERC20 _assetToken;
    IERC20 _guaranteeToken;
    uint _maxDeposit;
    uint _maxUsers;
    uint _minAmount;
    uint _fee;
    uint _guaranteeFee;
    uint _epochDuration;
    uint _lockPeriod;
    uint _feeDuration;
    address _investAddress;
    address[] _withdrawAddresses;
    bool _paused;
}

struct PairInfo {
    IUniswapV2Pair pair; //Uniswap Pair Address
    uint price0CumulativeLast;
    uint price1CumulativeLast;
    FixedPoint.uq112x112 price0Average; // First token average price
    FixedPoint.uq112x112 price1Average; // Second token average price
    uint32 blockTimestampLast; //Last time we calculate price
    address token0; // First token address
    address token1; // Second token address
}

interface ICivVault {
    function guaranteeFee() external view returns (uint);

    function feeBase() external view returns (uint);

    function getStrategyInfo(
        uint _id
    ) external view returns (StrategyInfo memory);

    function getEpochInfo(
        uint _id,
        uint _index
    ) external view returns (EpochInfo memory);

    function getCurrentEpoch(uint _id) external view returns (uint);

    function getUserInfo(
        uint _id,
        address _user
    ) external view returns (UserInfo memory);

    function getUserInfoEpoch(
        uint _id,
        address _user,
        uint _index
    ) external view returns (UserInfoEpoch memory);

    function getGuaranteeInfo(
        uint _idid,
        address _user,
        uint _index
    ) external view returns (GuaranteeInfo memory);
}

interface ICivFundRT is IERC20 {
    function decimals() external view returns (uint8);

    function mint(uint _amount) external returns (bool);

    function burn(uint _amount) external returns (bool);
}

interface ICivVaultGetter {
    function addUniPair(uint, address, address) external;

    function getPrice(uint, uint) external view returns (uint);

    function getReversePrice(uint, uint) external view returns (uint);

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

    function updateAll(uint) external;

    function addTimeOracle(uint, uint) external;

    function setEpochDuration(uint, uint) external;

    function getCurrentPeriod(uint) external view returns (uint);
}

interface IERC20Extended is IERC20 {
    function decimals() external view returns (uint);

    function symbol() external view returns (string memory);
}