// File: contracts/farming/Farming.sol



// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.17;

import './IFarming.sol';
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import 'contracts/lib/ownable/Ownable.sol';

struct Erc20Info {
    uint256 intervalNumber; // the last known claim interval (uses for update totalCountForClaim)
    uint256 totalCountOnInterval;
}

contract Farming is IFarming, Ownable {
    using SafeERC20 for IERC20;
    IERC20 immutable _stackingContract; // erc20 contract for stacking
    mapping(address => Stack) _stacks; // stacks by users
    uint256 constant _timeIntervalFirst = 7 days; // reward interval time length 0 interval
    uint256 _timeInterval = 7 days; // reward interval time length next intervals
    uint256 _nextIntervalTime; // next interval time
    uint256 _intervalNumber; // current interval number
    uint256 _totalStacksOnInterval; // current interval total stacks count
    uint256 _totalStacks; // total stacks count
    uint256 _totalEthOnInterval; // current interval eth rewards
    mapping(address => Erc20Info) _erc20nfos; // information about each erc20 (at current interval)
    mapping(address => uint256) _ethClaimIntervals; // users eth claim intervals
    mapping(address => mapping(address => uint256)) _erc20ClaimIntervals; // [account][erc20] cache of last erc20 claim intervals for accounts

    constructor(address stackingContract) {
        _stackingContract = IERC20(stackingContract);
        _nextIntervalTime = block.timestamp + _timeIntervalFirst;
    }

    receive() external payable {}

    function timeIntervalLength() external view returns (uint256) {
        if (_intervalNumber == 0 && block.timestamp < _nextIntervalTime)
            return _timeIntervalFirst;
        return _timeInterval;
    }

    function setTimeIntervalLengthHours(
        uint256 intervalHours
    ) external onlyOwner {
        _timeInterval = intervalHours * 1 hours;
    }

    function intervalNumber() external view returns (uint256) {
        uint256 intervals = _completedIntervals();
        if (intervals == 0) return _intervalNumber;
        return _intervalNumber + intervals;
    }

    function nextIntervalTime() external view returns (uint256) {
        uint256 intervals = _completedIntervals();
        if (intervals == 0) return _nextIntervalTime;
        return _nextIntervalTime + intervals * _timeInterval;
    }

    function nextIntervalLapsedSeconds() external view returns (uint256) {
        if (block.timestamp < _nextIntervalTime)
            return _nextIntervalTime - block.timestamp;
        return this.nextIntervalTime() - block.timestamp;
    }

    function _completedIntervals() internal view returns (uint256) {
        if (block.timestamp < _nextIntervalTime) return 0;
        return 1 + (block.timestamp - _nextIntervalTime) / _timeInterval;
    }

    function getStack(address account) external view returns (Stack memory) {
        return _stacks[account];
    }

    function addStack(uint256 count) external returns (Stack memory) {
        return _addStack(count);
    }

    function _addStack(uint256 count) internal returns (Stack memory) {
        _nextInterval();
        uint256 lastCount = _stackingContract.balanceOf(address(this));
        _stackingContract.transferFrom(msg.sender, address(this), count);
        uint256 added = _stackingContract.balanceOf(address(this)) - lastCount;
        _stacks[msg.sender].count += added;
        _stacks[msg.sender].creationInterval = _intervalNumber;
        _totalStacks += added;
        emit OnAddStack(msg.sender, _stacks[msg.sender], added);
        return _stacks[msg.sender];
    }

    function addFullStack() external returns (Stack memory) {
        return _addStack(_stackingContract.balanceOf(msg.sender));
    }

    function removeStack(uint256 count) external returns (Stack memory) {
        return _removeStack(count);
    }

    function _removeStack(uint256 count) internal returns (Stack memory) {
        _nextInterval();
        require(_stacks[msg.sender].count >= count, 'not enough stack count');
        uint256 lastCount = _stackingContract.balanceOf(address(this));
        _stackingContract.transfer(msg.sender, count);
        uint256 removed = lastCount -
            _stackingContract.balanceOf(address(this));
        _stacks[msg.sender].count -= removed;
        _stacks[msg.sender].creationInterval = _intervalNumber;
        _totalStacks -= removed;
        emit OnRemoveStack(msg.sender, _stacks[msg.sender], removed);
        return _stacks[msg.sender];
    }

    function removeFullStack() external returns (Stack memory) {
        return _removeStack(_stacks[msg.sender].count);
    }

    function totalStacks() external view returns (uint256) {
        return _totalStacks;
    }

    function totalStacksOnInterval() external view returns (uint256) {
        if (this.intervalNumber() <= _intervalNumber)
            return _totalStacksOnInterval;
        return _totalStacks;
    }

    function ethTotalForRewards() external view returns (uint256) {
        return address(this).balance;
    }

    function erc20TotalForRewards(
        address erc20
    ) external view returns (uint256) {
        if (erc20 == address(_stackingContract))
            return IERC20(erc20).balanceOf(address(this)) - _totalStacks;
        else return IERC20(erc20).balanceOf(address(this));
    }

    function ethOnInterval() external view returns (uint256) {
        if (this.intervalNumber() <= _intervalNumber)
            return _totalEthOnInterval;
        return this.ethTotalForRewards();
    }

    function erc20OnInterval(address erc20) external view returns (uint256) {
        return
            _expectedErc20Info(erc20, this.intervalNumber())
                .totalCountOnInterval;
    }

    function _expectedErc20Info(
        address erc20,
        uint256 expectedIntervalNumber
    ) internal view returns (Erc20Info memory) {
        Erc20Info memory info = _erc20nfos[erc20];
        if (expectedIntervalNumber <= info.intervalNumber) return info;
        info.intervalNumber = expectedIntervalNumber;
        info.totalCountOnInterval = this.erc20TotalForRewards(erc20);
        return info;
    }

    function ethClaimIntervalForAccount(
        address account
    ) external view returns (uint256) {
        uint256 interval = _ethClaimIntervals[account];
        if (_stacks[account].creationInterval + 1 > interval)
            interval = _stacks[account].creationInterval + 1;
        return interval + 1;
    }

    function erc20ClaimIntervalForAccount(
        address account,
        address erc20
    ) external view returns (uint256) {
        uint256 interval = _erc20ClaimIntervals[account][erc20];
        if (_stacks[account].creationInterval + 1 > interval)
            interval = _stacks[account].creationInterval + 1;
        return interval + 1;
    }

    function ethClaimCountForAccount(
        address account
    ) external view returns (uint256) {
        if (this.ethClaimIntervalForAccount(account) > this.intervalNumber())
            return 0;
        return this.ethClaimCountForStack(_stacks[account].count);
    }

    function erc20ClaimCountForAccount(
        address account,
        address erc20
    ) external view returns (uint256) {
        if (
            this.erc20ClaimIntervalForAccount(account, erc20) >
            this.intervalNumber()
        ) return 0;
        return this.erc20ClaimCountForStack(_stacks[account].count, erc20);
    }

    function ethClaimCountForAccountExpect(
        address account
    ) external view returns (uint256) {
        return this.ethClaimCountForStackExpect(_stacks[account].count);
    }

    function erc20ClaimCountForAccountExpect(
        address account,
        address erc20
    ) external view returns (uint256) {
        return
            this.erc20ClaimCountForStackExpect(_stacks[account].count, erc20);
    }

    function ethClaimCountForStackExpect(
        uint256 stackSize
    ) external view returns (uint256) {
        return
            _claimCountForStack(
                stackSize,
                this.totalStacks(),
                this.ethTotalForRewards()
            );
    }

    function erc20ClaimCountForStackExpect(
        uint256 stackSize,
        address erc20
    ) external view returns (uint256) {
        return
            _claimCountForStack(
                stackSize,
                this.totalStacks(),
                this.erc20TotalForRewards(erc20)
            );
    }

    function ethClaimCountForNewStackExpect(
        uint256 stackSize
    ) external view returns (uint256) {
        return
            _claimCountForStack(
                stackSize,
                this.totalStacks() + stackSize,
                this.ethTotalForRewards()
            );
    }

    function erc20ClaimCountForNewStackExpect(
        uint256 stackSize,
        address erc20
    ) external view returns (uint256) {
        return
            _claimCountForStack(
                stackSize,
                this.totalStacks() + stackSize,
                this.erc20TotalForRewards(erc20)
            );
    }

    function ethClaimCountForStack(
        uint256 stackSize
    ) external view returns (uint256) {
        return
            _claimCountForStack(
                stackSize,
                this.totalStacksOnInterval(),
                this.ethOnInterval()
            );
    }

    function erc20ClaimCountForStack(
        uint256 stackSize,
        address erc20
    ) external view returns (uint256) {
        return
            _claimCountForStack(
                stackSize,
                this.totalStacksOnInterval(),
                this.erc20OnInterval(erc20)
            );
    }

    function _claimCountForStack(
        uint256 stackCount,
        uint256 totalStacksOnInterwal,
        uint256 assetCountOnInterwal
    ) internal pure returns (uint256) {
        if (stackCount > totalStacksOnInterwal) return assetCountOnInterwal;
        if (totalStacksOnInterwal == 0) return 0;
        return (stackCount * assetCountOnInterwal) / totalStacksOnInterwal;
    }

    function erc20ClaimForStack(
        address erc20,
        uint256 stackCount
    ) external view returns (uint256) {
        return
            _claimCountForStack(
                stackCount,
                this.totalStacksOnInterval(),
                this.erc20OnInterval(erc20)
            );
    }

    function _nextInterval() internal returns (bool) {
        if (block.timestamp < _nextIntervalTime) return false;
        _totalStacksOnInterval = this.totalStacks();
        _intervalNumber = this.intervalNumber();
        _nextIntervalTime = this.nextIntervalTime();
        _totalEthOnInterval = this.ethTotalForRewards();
        emit OnNextInterval(_intervalNumber);
        return true;
    }

    function claimEth() external {
        _claimEth();
    }

    function _claimEth() internal {
        _nextInterval();
        require(
            this.ethClaimIntervalForAccount(msg.sender) <= _intervalNumber,
            'can not claim on current interval'
        );
        _ethClaimIntervals[msg.sender] = _intervalNumber;
        uint256 claimCount = _claimCountForStack(
            _stacks[msg.sender].count,
            _totalStacksOnInterval,
            _totalEthOnInterval
        );
        require(claimCount > 0, 'notging to claim');
        (bool sent, ) = payable(msg.sender).call{ value: claimCount }('');
        require(sent, 'sent ether error: ether is not sent');
        emit OnClaimEth(msg.sender, _stacks[msg.sender], claimCount);
    }

    function claimErc20(address erc20) external {
        _claimErc20(erc20);
    }

    function _claimErc20(address erc20) internal {
        // move interval
        _nextInterval();
        // move erc20 to interval
        Erc20Info storage info = _erc20nfos[erc20];
        if (_intervalNumber > info.intervalNumber) {
            info.intervalNumber = _intervalNumber;
            info.totalCountOnInterval = this.erc20TotalForRewards(erc20);
        }

        require(
            this.erc20ClaimIntervalForAccount(msg.sender, erc20) <=
                _intervalNumber,
            'can not claim on current interval'
        );
        _erc20ClaimIntervals[msg.sender][erc20] = _intervalNumber;
        uint256 claimCount = _claimCountForStack(
            _stacks[msg.sender].count,
            _totalStacksOnInterval,
            info.totalCountOnInterval
        );
        require(claimCount > 0, 'nothing to claim');
        IERC20(erc20).safeTransfer(msg.sender, claimCount);
        emit OnClaimErc20(msg.sender, _stacks[msg.sender], claimCount);
    }

    function batchClaim(bool claimEth, address[] calldata tokens) external {
        if (claimEth) _claimEth();
        for (uint256 i = 0; i < tokens.length; ++i) _claimErc20(tokens[i]);
    }
}

// File: contracts/farming/IFarming.sol



// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.17;

struct Stack {
    uint256 count; // the stack size
    uint256 creationInterval; // creation or edit interval
}

interface IFarming {
    /// @dev account added stack count
    event OnAddStack(address indexed account, Stack stack, uint256 count);
    /// @dev account removed stack count
    event OnRemoveStack(address indexed account, Stack stack, uint256 count);
    /// @dev account claimed eth
    event OnClaimEth(address indexed account, Stack stack, uint256 count);
    /// @dev account claimed erc20
    event OnClaimErc20(address indexed account, Stack stack, uint256 count);
    /// @dev next interval
    event OnNextInterval(uint256 interval);

    /// @dev the intervals time length
    function timeIntervalLength() external view returns (uint256);

    /// @dev sets time interval number in hours
    /// onlyOwner
    function setTimeIntervalLengthHours(uint256 intervalHours) external;

    /// @dev current interval number
    function intervalNumber() external view returns (uint256);

    /// @dev time of next interval. Can be less then current time if if next interwal is already started, but no one write function has been at new interval
    function nextIntervalTime() external view returns (uint256);

    /// @dev next interval lapsed seconds or 0 if next interwal is already started, but no one write function has been at new interval
    function nextIntervalLapsedSeconds() external view returns (uint256);

    /// @dev returns the accounts stack
    function getStack(address account) external view returns (Stack memory);

    /// @dev adds the accounts stack
    function addStack(uint256 count) external returns (Stack memory);

    /// @dev adds the caller all fee tokens to stack
    function addFullStack() external returns (Stack memory);

    /// @dev reves the accounts stack
    function removeStack(uint256 count) external returns (Stack memory);

    /// @dev removes the caller all fee tokens from stack
    function removeFullStack() external returns (Stack memory);

    /// @dev total stacks erc20 count
    function totalStacks() external view returns (uint256);

    /// @dev returns the total fee tokens stacked at current interval
    function totalStacksOnInterval() external view returns (uint256);

    /// @dev returns total eth for rewards
    function ethTotalForRewards() external view returns (uint256);

    /// @dev returns total erc20 for rewards
    function erc20TotalForRewards(address erc20) external view returns (uint256);

    /// @dev returns total eth at current interval
    function ethOnInterval() external view returns (uint256);

    /// @dev returns total erc20 at current interval
    function erc20OnInterval(address erc20) external view returns (uint256);

    /// @dev the interval from which an account can claim ethereum rewards
    /// sets to next interval if add stack or claim eth
    function ethClaimIntervalForAccount(
        address account
    ) external view returns (uint256);

    /// @dev the interval from which an account can claim erc20 rewards
    /// sets to next interval if add stack or claim eth
    function erc20ClaimIntervalForAccount(
        address account,
        address erc20
    ) external view returns (uint256);

    /// @dev returns eth that would be claimed by account at current time
    function ethClaimCountForAccount(
        address account
    ) external view returns (uint256);

    /// @dev returns erc20 that would be claimed by account at current time
    function erc20ClaimCountForAccount(
        address account,
        address erc20
    ) external view returns (uint256);

    /// @dev returns expected eth that would be claimed by account at current time (on all intervals)
    function ethClaimCountForAccountExpect(
        address account
    ) external view returns (uint256);

    /// @dev returns expected erc20 that would be claimed by account at current time (on all intervals)
    function erc20ClaimCountForAccountExpect(
        address account,
        address erc20
    ) external view returns (uint256);

    /// @dev returns expected eth claim count for stack size at current time (on all intervals)
    function ethClaimCountForStackExpect(
        uint256 stackSize
    ) external view returns (uint256);

    /// @dev returns expected erc20 that would be claimed for stack size at current time (on all intervals)
    function erc20ClaimCountForStackExpect(
        uint256 stackSize,
        address erc20
    ) external view returns (uint256);

    /// @dev returns expected eth claim count for new stack size at current time (on all intervals)
    function ethClaimCountForNewStackExpect(
        uint256 stackSize
    ) external view returns (uint256);

    /// @dev returns expected erc20 that would be claimed for new stack size at current time (on all intervals)
    function erc20ClaimCountForNewStackExpect(
        uint256 stackSize,
        address erc20
    ) external view returns (uint256);

    /// @dev returns eth claim count for stack on interval
    function ethClaimCountForStack(
        uint256 stackSize
    ) external view returns (uint256);

    /// @dev returns erc20 that would be claimed for stack size at current time
    function erc20ClaimCountForStack(
        uint256 stackSize,
        address erc20
    ) external view returns (uint256);

    /// @dev claims ethereum
    function claimEth() external;

    /// @dev claims certain erc20
    function claimErc20(address erc20) external;

    /// @dev batch claim ethereum and or erc20 tokens
    function batchClaim(bool claimEth, address[] calldata tokens) external;
}

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



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

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/draft-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;

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    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));
    }

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    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");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    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");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.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: contracts/lib/ownable/Ownable.sol



// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.17;

import './IOwnable.sol';

contract Ownable is IOwnable {
    address _owner;

    constructor() {
        _owner = msg.sender;
    }

    modifier onlyOwner() {
        require(_owner == msg.sender, 'caller is not the owner');
        _;
    }

    function owner() external virtual view returns (address) {
        return _owner;
    }

    function transferOwnership(address newOwner) external override onlyOwner {
        _owner = newOwner;
    }
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-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/utils/Address.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.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
     * ====
     *
     * [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://diligence.consensys.net/posts/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.5.11/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 functionCall(target, data, "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");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(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) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(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) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason 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 {
            // 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: contracts/lib/ownable/IOwnable.sol



// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.17;

interface IOwnable {
    function owner() external view returns (address);

    function transferOwnership(address newOwner) external;
}