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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (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. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    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: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol



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



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: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol



pragma solidity >=0.6.2;

interface IUniswapV2Router01 {
    function factory() external pure returns (address);
    function WETH() external pure returns (address);

    function addLiquidity(
        address tokenA,
        address tokenB,
        uint amountADesired,
        uint amountBDesired,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB, uint liquidity);
    function addLiquidityETH(
        address token,
        uint amountTokenDesired,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external payable returns (uint amountToken, uint amountETH, uint liquidity);
    function removeLiquidity(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETH(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountToken, uint amountETH);
    function removeLiquidityWithPermit(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETHWithPermit(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountToken, uint amountETH);
    function swapExactTokensForTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapTokensForExactTokens(
        uint amountOut,
        uint amountInMax,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);
    function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);

    function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
    function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
    function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}

// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol



pragma solidity >=0.6.2;

import './IUniswapV2Router01.sol';

interface IUniswapV2Router02 is IUniswapV2Router01 {
    function removeLiquidityETHSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountETH);
    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountETH);

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
    function swapExactETHForTokensSupportingFeeOnTransferTokens(
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable;
    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
}

// File: contracts/CoinGenie.sol



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

/*
            ██████                                                                                  
           ████████         █████████     ██████████     ███  ████         ███                      
            ██████        █████████████ ██████████████   ████ ██████      ████                      
              ██        ████████  ████ ██████    ██████  ████ ███████     ████                      
              ██       █████          █████        █████ ████ █████████   ████                      
              ██       █████          ████         █████ ████ ████ ██████ ████                      
             ████      █████          ████         █████ ████ ████  ██████████                      
            █████       █████         █████        █████ ████ ████    ████████                      
           ████████      █████████████ ████████████████  ████ ████     ███████                      
          ████  ████      █████████████  ████████████    ████ ████       █████                      
        █████    █████        █████          ████                                                   
      ██████      ██████                                                                            
    ██████         ███████                                                                          
  ████████          ████████           ███████████  █████████████████        ████  ████ ████████████
 ████████           █████████        █████████████  ███████████████████      ████ █████ ████████████
█████████           ██████████     ███████          █████        ████████    ████ █████ ████        
██████████         ████████████    █████            █████        █████████   ████ █████ ████        
██████████████   ██████████████    █████   ████████ ████████████ ████ ██████ ████ █████ ███████████ 
███████████████████████████████    █████   ████████ ██████████   ████  ██████████ █████ ██████████  
███████████████████████████████    ██████      ████ █████        ████    ████████ █████ ████        
 █████████████████████████████      ███████████████ ████████████ ████      ██████ █████ ████████████
  ██████████████████████████          █████████████ █████████████████       █████ █████ ████████████
 */

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";

import { IUniswapV2Router02 } from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";

import { Payments } from "./abstract/Payments.sol";

import { CoinGenieERC20 } from "./token/CoinGenieERC20.sol";
import { ICoinGenieERC20 } from "./token/ICoinGenieERC20.sol";

/**
 * /// @title CoinGenie
 * /// @author @neuro_0x
 * /// @dev The orchestrator contract for the CoinGenie ecosystem.
 */
contract CoinGenie is Payments {
    /// @dev Struct to hold token details
    struct LaunchedToken {
        string name;
        string symbol;
        address tokenAddress;
        address payable feeRecipient;
        address payable affiliateFeeRecipient;
        uint256 index;
        uint256 totalSupply;
        uint256 taxPercent;
        uint256 maxBuyPercent;
        uint256 maxWalletPercent;
    }

    /// @dev Payout categories
    enum PayoutCategory {
        Treasury,
        Dev,
        Legal,
        Marketing
    }

    /// @dev Payouts
    struct Payout {
        address payable receiver;
        uint256 share;
    }

    /// @dev The address of the Uniswap V2 Router
    IUniswapV2Router02 private constant _UNISWAP_V2_ROUTER =
        IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);

    /// @dev The maximum percent in basis points that can be used as a discount
    uint256 private constant _MAX_BPS = 10_000;

    /// @dev The percent in basis points to use as coin genie fee
    uint256 private _coinGenieFeePercent = 100;

    /// @dev The percent in basis points to use as a discount if paying in $GENIE
    uint256 private _discountPercent = 5000;

    /// @dev The amount of $GENIE a person has to pay to get the discount
    uint256 private _discountFeeRequiredAmount = 100_000 ether;

    /// @dev A mapping of a payout category to a payout
    mapping(PayoutCategory category => Payout payout) private _payouts;

    /// @dev The array of launched token addresses
    address[] public launchedTokens;

    /// @dev The array of users
    address[] public users;

    /// @dev The array of created claimable airdrop addresses
    address[] public createdClaimableAirdrops;

    /// @dev A mapping of a token address to its details
    mapping(address token => LaunchedToken launchedToken) public launchedTokenDetails;

    /// @dev A mapping of a user to the tokens they have launched
    mapping(address user => LaunchedToken[] tokens) public tokensLaunchedBy;

    /////////////////////////////////////////////////////////////////
    //                           Events                            //
    /////////////////////////////////////////////////////////////////

    /// @notice Emits when the discount percent is set
    /// @param percent - the percent in basis points to use as a discount
    event DiscountPercentSet(uint256 indexed percent);

    /// @notice Emits when the discount fee required amount is set
    /// @param amount - the amount of $GENIE a person has to hold to get the discount
    event DiscountFeeRequiredAmountSet(uint256 indexed amount);

    /// @notice Emitted when a token is launched
    /// @param newTokenAddress - the address of the new token
    /// @param tokenOwner - the address of the token owner
    event ERC20Launched(address indexed newTokenAddress, address indexed tokenOwner);

    /////////////////////////////////////////////////////////////////
    //                           Errors                            //
    /////////////////////////////////////////////////////////////////

    /// @notice Reverts when approving a token fails
    error ApprovalFailed();

    /// @notice Reverts when the caller is not a team member
    /// @param caller - the caller of the function
    error NotTeamMember(address caller);

    /// @notice Reverts when the share is too high
    /// @param share - the share amount
    /// @param maxShare - the max share amount
    error ShareToHigh(uint256 share, uint256 maxShare);

    /// @notice Reverts when the payout category is invalid
    /// @param category - the payout category
    error InvalidPayoutCategory(PayoutCategory category);

    /// @notice Reverts when the discount percent exceeds the max percent
    /// @param percent - the percent in basis points to use as a discount
    /// @param maxBps - the max percent in basis points
    error ExceedsMaxDiscountPercent(uint256 percent, uint256 maxBps);

    /// @notice Reverts when the coin genie fee percent exceeds the max percent
    /// @param percent - the percent in basis points to use as a fee
    /// @param maxBps - the max percent in basis points
    error ExceedsMaxFeePercent(uint256 percent, uint256 maxBps);

    /// @notice Construct the CoinGenie contract.
    constructor() payable {
        address[] memory payees = new address[](4);
        uint256[] memory shares_ = new uint256[](4);

        payees[0] = 0xBe79b43B1505290DFE04294a433963dbeea736BB; // treasury
        payees[1] = 0x3fB2120fc0CD15000d2e500Efbdd9CE17356E242; // dev
        payees[2] = 0xF14A30C09897d2C7481c5907D01Ec58Ec09555af; // marketing
        payees[3] = 0xbb6712A513C2d7F3E17A40d095a773c5d98574B2; // legal

        shares_[0] = 20;
        shares_[1] = 50;
        shares_[2] = 25;
        shares_[3] = 5;

        _createSplit(payees, shares_);
    }

    /////////////////////////////////////////////////////////////////
    //                      Public/External                        //
    /////////////////////////////////////////////////////////////////

    receive() external payable override {
        address from = _msgSender();
        // If we are receiving ETH from a Coin Genie token, then we need to send the affiliate fee
        if (launchedTokenDetails[from].tokenAddress == from) {
            address payable affiliate = launchedTokenDetails[from].affiliateFeeRecipient;
            uint256 affiliateAmount = (msg.value * _affiliateFeePercent) / _MAX_BPS;

            if (affiliateAmount != 0 && affiliate != address(0) && affiliate != address(this)) {
                _affiliatePayoutOwed += affiliateAmount;
                _amountReceivedFromAffiliate[affiliate] += msg.value;
                _amountOwedToAffiliate[affiliate] += affiliateAmount;
                _amountEarnedByAffiliateByToken[affiliate][from] += affiliateAmount;

                if (!_isTokenReferredByAffiliate[affiliate][from]) {
                    _isTokenReferredByAffiliate[affiliate][from] = true;

                    if (_tokensReferredByAffiliate[affiliate].length == 0) {
                        affiliates.push(affiliate);
                    }

                    _tokensReferredByAffiliate[affiliate].push(from);
                }
            }

            emit PaymentReceived(from, msg.value);
        } else {
            emit PaymentReceived(from, msg.value);
        }
    }

    /// @notice Gets the address of the $GENIE contract
    /// @return the address of the $GENIE contract
    function genie() public view returns (address payable) {
        return payable(launchedTokens[0]);
    }

    /// @notice Gets the percent in basis points to use as coin genie fee
    /// @return the percent in basis points to use as coin genie fee
    function coinGenieFeePercent() public view returns (uint256) {
        return _coinGenieFeePercent;
    }

    /// @notice Gets the discount percent
    /// @return the discount percent
    function discountPercent() external view returns (uint256) {
        return _discountPercent;
    }

    /// @notice Gets the discount fee required amount
    /// @return the discount fee required amount
    function discountFeeRequiredAmount() external view returns (uint256) {
        return _discountFeeRequiredAmount;
    }

    /// @notice Launch a new instance of the ERC20.
    /// @dev This function deploys a new token contract and initializes it with provided parameters.
    /// @param name - the name of the token
    /// @param symbol - the ticker symbol of the token
    /// @param totalSupply - the totalSupply of the token
    /// @param affiliateFeeRecipient - the address to receive the affiliate fee
    /// @param taxPercent - the percent in basis points to use as a tax
    /// @param maxBuyPercent - amount of tokens allowed to be transferred in one tx as a percent of the total supply
    /// @param maxWalletPercent - amount of tokens allowed to be held in one wallet as a percent of the total supply
    /// @return newToken  - the CoinGenieERC20 token created
    function launchToken(
        string memory name,
        string memory symbol,
        uint256 totalSupply,
        address affiliateFeeRecipient,
        uint256 taxPercent,
        uint256 maxBuyPercent,
        uint256 maxWalletPercent
    )
        external
        returns (ICoinGenieERC20 newToken)
    {
        address payable feeRecipient = payable(msg.sender);
        if (affiliateFeeRecipient == address(0)) {
            affiliateFeeRecipient = payable(address(this));
        }

        // Deploy the token contract
        newToken = new CoinGenieERC20(
            name,
            symbol,
            totalSupply,
            feeRecipient,
            payable(address(this)),
            payable(affiliateFeeRecipient),
            taxPercent,
            maxBuyPercent,
            maxWalletPercent,
            _discountFeeRequiredAmount,
            _discountPercent
        );

        // Add the user to the array of users
        if (tokensLaunchedBy[feeRecipient].length == 0) {
            users.push(feeRecipient);
        }

        // Add the token address to the array of launched token addresses
        launchedTokens.push(address(newToken));

        // Create a new LaunchedToken struct
        LaunchedToken memory launchedToken = LaunchedToken({
            index: launchedTokens.length - 1,
            tokenAddress: address(newToken),
            name: name,
            symbol: symbol,
            totalSupply: totalSupply,
            feeRecipient: feeRecipient,
            affiliateFeeRecipient: payable(affiliateFeeRecipient),
            taxPercent: taxPercent,
            maxBuyPercent: maxBuyPercent,
            maxWalletPercent: maxWalletPercent
        });

        if (tokensLaunchedBy[feeRecipient].length != 0) {
            // If the token is not a new user, update the affiliateFeeRecipient to be their first one
            launchedToken.affiliateFeeRecipient = tokensLaunchedBy[feeRecipient][0].affiliateFeeRecipient;
        }

        // Add the token to the array of tokens launched by the fee recipient
        tokensLaunchedBy[feeRecipient].push(launchedToken);

        // Add the token details to the mapping of launched tokens
        launchedTokenDetails[address(newToken)] = launchedToken;

        // Set the genie token address
        newToken.setGenie(payable(launchedTokens[0]));

        // Set the coin genie fee percent
        newToken.setCoinGenieFeePercent(_coinGenieFeePercent);

        // Assign ownership to the fee recipient
        Ownable(address(newToken)).transferOwnership(feeRecipient);

        // Emit the event
        emit ERC20Launched(address(newToken), msg.sender);
    }

    /// @notice Gets the number of tokens that have been launched.
    function getNumberOfLaunchedTokens() external view returns (uint256) {
        return launchedTokens.length;
    }

    /// @notice Get the launched tokens.
    /// @param _address The address to get the tokens for
    /// @return tokens The array of launched tokens
    function getLaunchedTokensForAddress(address _address) external view returns (LaunchedToken[] memory tokens) {
        return tokensLaunchedBy[_address];
    }

    /// @notice Set the coin genie fee percent for tokens
    /// @param percent The percent in basis points to use as coin genie fee
    function setCoinGenieFeePercent(uint256 percent) external onlyOwner {
        if (percent > _MAX_BPS) {
            revert ExceedsMaxFeePercent(percent, _MAX_BPS);
        }

        _coinGenieFeePercent = percent;
    }

    /// @dev Allows the owner to set the percent in basis points to use as a discount
    /// @param percent - the percent in basis points to use as a discount
    function setDiscountPercent(uint256 percent) external onlyOwner {
        if (percent > _MAX_BPS) {
            revert ExceedsMaxDiscountPercent(percent, _MAX_BPS);
        }

        _discountPercent = percent;
        emit DiscountPercentSet(percent);
    }

    /// @dev Allows the owner to set the amount of $GENIE required to get the discount
    /// @param amount - the amount of $GENIE a person has to hold to get the discount
    function setDiscountFeeRequiredAmount(uint256 amount) external onlyOwner {
        _discountFeeRequiredAmount = amount;
        emit DiscountFeeRequiredAmountSet(amount);
    }

    /// @notice Swaps tokens for Ether.
    /// @dev Utilizes Uniswap for the token-to-ETH swap.
    /// @param tokenAmount The amount of tokens to swap for ETH.
    function swapGenieForEth(uint256 tokenAmount) external nonReentrant onlyOwner {
        ICoinGenieERC20 genieToken = ICoinGenieERC20(launchedTokens[0]);
        address[] memory path = new address[](2);
        path[0] = address(genieToken);
        path[1] = _UNISWAP_V2_ROUTER.WETH();
        genieToken.approve(address(_UNISWAP_V2_ROUTER), tokenAmount);
        _UNISWAP_V2_ROUTER.swapExactTokensForETHSupportingFeeOnTransferTokens(
            tokenAmount, 0, path, address(this), block.timestamp
        );
    }
}

// File: contracts/abstract/Payments.sol



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

/*
            ██████                                                                                  
           ████████         █████████     ██████████     ███  ████         ███                      
            ██████        █████████████ ██████████████   ████ ██████      ████                      
              ██        ████████  ████ ██████    ██████  ████ ███████     ████                      
              ██       █████          █████        █████ ████ █████████   ████                      
              ██       █████          ████         █████ ████ ████ ██████ ████                      
             ████      █████          ████         █████ ████ ████  ██████████                      
            █████       █████         █████        █████ ████ ████    ████████                      
           ████████      █████████████ ████████████████  ████ ████     ███████                      
          ████  ████      █████████████  ████████████    ████ ████       █████                      
        █████    █████        █████          ████                                                   
      ██████      ██████                                                                            
    ██████         ███████                                                                          
  ████████          ████████           ███████████  █████████████████        ████  ████ ████████████
 ████████           █████████        █████████████  ███████████████████      ████ █████ ████████████
█████████           ██████████     ███████          █████        ████████    ████ █████ ████        
██████████         ████████████    █████            █████        █████████   ████ █████ ████        
██████████████   ██████████████    █████   ████████ ████████████ ████ ██████ ████ █████ ███████████ 
███████████████████████████████    █████   ████████ ██████████   ████  ██████████ █████ ██████████  
███████████████████████████████    ██████      ████ █████        ████    ████████ █████ ████        
 █████████████████████████████      ███████████████ ████████████ ████      ██████ █████ ████████████
  ██████████████████████████          █████████████ █████████████████       █████ █████ ███████████
*/

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol";

import { IUniswapV2Router02 } from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";

/**
 * @title Payments
 * @author @neuro_0x
 * @notice This contract is used to split payments between multiple parties, and track and affiliates and their fees
 */
abstract contract Payments is Ownable, ReentrancyGuard {
    /// @dev The maximum amount of basis points
    uint256 private constant _MAX_BPS = 10_000;

    /// @dev The maximum shares
    uint256 private constant _MAX_SHARES = 100;

    /// @dev The address of the Uniswap V2 Router
    IUniswapV2Router02 private constant _UNISWAP_V2_ROUTER =
        IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);

    /// @dev The total amount of shares
    uint256 internal _totalShares;

    /// @dev The total amount of released payments
    uint256 internal _totalReleased;

    /// @dev The total amount of affiliate fees owed
    uint256 internal _affiliatePayoutOwed;

    /// @dev The affiliate fee percentage
    uint256 internal _affiliateFeePercent = 2000;

    /// @dev The mapping of shares for each payee
    mapping(address payee => uint256 shares) internal _shares;

    /// @dev The mapping of released payments for each payee
    mapping(address payee => uint256 released) internal _released;

    /// @dev The mapping of amount received from each affiliate
    mapping(address affiliate => uint256 amountReceived) internal _amountReceivedFromAffiliate;

    /// @dev The mapping of amount paid to each affiliate
    mapping(address affiliate => uint256 amountPaid) internal _amountPaidToAffiliate;

    /// @dev The mapping of amount owed to each affiliate
    mapping(address affiliate => uint256 amountOwed) internal _amountOwedToAffiliate;

    /// @dev The mapping of tokens referred by each affiliate
    mapping(address affiliate => address[] tokensReferred) internal _tokensReferredByAffiliate;

    /// @dev The mapping of tokens referred by each affiliate
    mapping(address affiliate => mapping(address tokenAddress => bool)) internal _isTokenReferredByAffiliate;

    /// @dev The mapping of amount earned by each affiliate for each token
    mapping(address affiliate => mapping(address tokenAddress => uint256 amountOwed)) internal
        _amountEarnedByAffiliateByToken;

    /// @dev The array of payees
    address[] private _payees;

    /// @dev The array of affiliates
    address[] public affiliates;

    /////////////////////////////////////////////////////////////////
    //                          Events                             //
    /////////////////////////////////////////////////////////////////

    /// @dev The event emitted when a share is updated
    /// @param account the account that was updated
    /// @param shares the amount of shares for the account
    event ShareUpdated(address indexed account, uint256 indexed shares);

    /// @dev The event emitted when a payee is added
    /// @param account the payee account
    /// @param shares the amount of shares for the payee
    event PayeeAdded(address indexed account, uint256 indexed shares);

    /// @dev The event emitted when a payment is released
    /// @param to the account to release payment to
    /// @param amount the amount of payment released
    event PaymentReleased(address indexed to, uint256 indexed amount);

    /// @dev The event emitted when a payment is received
    /// @param from the account that sent the payment
    /// @param amount the amount of payment received
    event PaymentReceived(address indexed from, uint256 indexed amount);

    /////////////////////////////////////////////////////////////////
    //                          Errors                             //
    /////////////////////////////////////////////////////////////////

    /// @dev The error emitted when there are no payees
    error NoPayees();

    /// @dev The error emitted when a payment fails
    error PaymentFailed();

    /// @dev The error emitted when shares are zero
    error SharesAreZero();

    /// @dev The error emitted when the genie is already set
    error GenieAlreadySet();

    /// @dev The error emitted when the account is a zero address
    error AccountIsZeroAddress();

    /// @dev The error emitted when there is no amount owed to an affiliate
    error NoAmountOwedToAffiliate();

    /// @dev The error emitted when an account already has shares
    error AccountAlreadyHasShares();

    /// @dev The error emitted when the shares are invalid
    /// @param shares the amount of shares
    error InvalidShares(uint256 shares);

    /// @dev The error emitted when an account is not due payment
    /// @param account the account that is not due payment
    error AccountNotDuePayment(address account);

    /// @dev The error emitted when there are no shares for an account
    /// @param account the account that has no shares
    error ZeroSharesForAccount(address account);

    /// @dev The error emitted when the affiliate percent is invalid
    /// @param affiliatePercent the affiliate percent
    /// @param maxBps the maximum basis points
    error InvalidAffiliatePercent(uint256 affiliatePercent, uint256 maxBps);

    /// @dev The error emitted when the payee and shares lengths do not match
    /// @param payeesLength the length of the payees array
    /// @param sharesLength the length of the shares array
    error PayeeShareLengthMisMatch(uint256 payeesLength, uint256 sharesLength);

    /////////////////////////////////////////////////////////////////
    //                     Public/External                         //
    /////////////////////////////////////////////////////////////////

    /// @dev Extending contract should override this function and emit this event
    receive() external payable virtual {
        emit PaymentReceived(_msgSender(), msg.value);
    }

    /// @return the total amount of shares
    function totalShares() public view returns (uint256) {
        return _totalShares;
    }

    /// @return the total amount of released payments
    function totalReleased() public view returns (uint256) {
        return _totalReleased;
    }

    /// @param account the account to get the shares for
    /// @return the amount of shares for an account
    function shares(address account) public view returns (uint256) {
        return _shares[account];
    }

    /// @param account the account to get the released payments for
    /// @return the amount of released payments for an account
    function released(address account) public view returns (uint256) {
        return _released[account];
    }

    /// @param index the index of the payee to get
    /// @return the address of the payee
    function payee(uint256 index) public view returns (address) {
        return _payees[index];
    }

    /// @return the number of payees
    function payeeCount() public view returns (uint256) {
        return _payees.length;
    }

    /// @return the total amount of affiliate fees owed
    function amountOwedToAllAffiliates() public view returns (uint256) {
        return _affiliatePayoutOwed;
    }

    /// @param account the affiliate account to get the amount owed to
    /// @return the total amount owed to an affiliate
    function amountOwedToAffiliate(address account) public view returns (uint256) {
        return _amountOwedToAffiliate[account];
    }

    /// @param account the affiliate account to get the amount paid to
    /// @return the total amount paid to an affiliate
    function amountPaidToAffiliate(address account) public view returns (uint256) {
        return _amountPaidToAffiliate[account];
    }

    /// @return the array of affiliates
    function getAffiliates() public view returns (address[] memory) {
        return affiliates;
    }

    /// @return the number of affiliates
    function getNumberOfAffiliates() public view returns (uint256) {
        return affiliates.length;
    }

    /// @param account the affiliate account to get the tokens referred by
    /// @return the tokens referred by an affiliate
    function getTokensReferredByAffiliate(address account) public view returns (address[] memory) {
        return _tokensReferredByAffiliate[account];
    }

    /// @param account the affiliate account to get the amount earned from
    /// @param tokenAddress the token address to get the amount earned from
    /// @return the amount earned from an affiliate for a token
    function amountEarnedByAffiliateByToken(address account, address tokenAddress) public view returns (uint256) {
        return _amountEarnedByAffiliateByToken[account][tokenAddress];
    }

    /// @return the affiliate fee percent
    function affiliateFeePercent() public view returns (uint256) {
        return _affiliateFeePercent;
    }

    /// @param account the affiliate to release payment to
    /// @param genie_ the address of the CoinGenie ERC20 $GENIE token
    function affiliateRelease(address payable account, address genie_) external nonReentrant {
        uint256 payment = _amountOwedToAffiliate[account];

        if (payment == 0) {
            revert NoAmountOwedToAffiliate();
        }

        _amountOwedToAffiliate[account] = 0;
        _amountPaidToAffiliate[account] += payment;

        _affiliatePayoutOwed -= payment;

        if (account == address(this)) {
            (bool success,) = account.call{ value: payment }("");
            if (!success) {
                revert PaymentFailed();
            }
        } else {
            address[] memory path = new address[](2);
            path[0] = _UNISWAP_V2_ROUTER.WETH();
            path[1] = genie_;
            _UNISWAP_V2_ROUTER.swapExactETHForTokensSupportingFeeOnTransferTokens{ value: payment }(
                0, path, account, block.timestamp
            );
        }

        emit PaymentReleased(account, payment);
    }

    /// @dev Set the affiliate fee percent
    /// @param newAffiliatePercent the new affiliate percent
    function setAffiliatePercent(uint256 newAffiliatePercent) external onlyOwner {
        if (newAffiliatePercent > _MAX_BPS) {
            revert InvalidAffiliatePercent(newAffiliatePercent, _MAX_BPS);
        }

        _affiliateFeePercent = newAffiliatePercent;
    }

    /// @dev Pay a team member
    /// @param account the account to release payment to
    function release(address payable account) external virtual nonReentrant {
        if (_shares[account] == 0) {
            revert ZeroSharesForAccount(account);
        }

        uint256 totalReceived = address(this).balance - _affiliatePayoutOwed + _totalReleased;
        uint256 payment = _pendingPayment(account, totalReceived, released(account));

        if (payment == 0) {
            revert AccountNotDuePayment(account);
        }

        _released[account] += payment;
        _totalReleased += payment;

        (bool success,) = account.call{ value: payment }("");
        if (!success) {
            revert PaymentFailed();
        }

        emit PaymentReleased(account, payment);
    }

    /// @dev Update the split
    /// @param payees_ the payees
    /// @param shares_ the shares of the payees
    function updateSplit(address[] calldata payees_, uint256[] calldata shares_) external onlyOwner {
        uint256 len = payees_.length;
        if (len != shares_.length) {
            revert PayeeShareLengthMisMatch(len, shares_.length);
        }

        if (len == 0) {
            revert NoPayees();
        }

        uint256 sumShares;
        for (uint256 i = 0; i < len;) {
            sumShares += shares_[i];

            unchecked {
                i = i + 1;
            }
        }

        if (sumShares != _MAX_SHARES) {
            revert InvalidShares(sumShares);
        }

        // Reset current shares
        uint256 currentLength = _payees.length;
        for (uint256 i = 0; i < currentLength;) {
            delete _shares[payees_[i]];

            unchecked {
                i = i + 1;
            }
        }

        // Add new shares and payees
        _payees = new address[](0);
        for (uint256 i = 0; i < len;) {
            _addPayee(payees_[i], shares_[i]);

            unchecked {
                i = i + 1;
            }
        }
    }

    /////////////////////////////////////////////////////////////////
    //                     Private/Internal                        //
    /////////////////////////////////////////////////////////////////

    /// @dev Called on contract creation to set the initial payees and shares
    /// @param payees the array of payees
    /// @param shares_ the array of shares
    function _createSplit(address[] memory payees, uint256[] memory shares_) internal {
        uint256 len = payees.length;
        if (len != shares_.length) {
            revert PayeeShareLengthMisMatch(len, shares_.length);
        }

        if (len == 0) {
            revert NoPayees();
        }

        uint256 sumShares;
        for (uint256 i = 0; i < len;) {
            sumShares += shares_[i];

            unchecked {
                i = i + 1;
            }
        }

        if (sumShares != _MAX_SHARES) {
            revert InvalidShares(sumShares);
        }

        for (uint256 i = 0; i < len;) {
            _addPayee(payees[i], shares_[i]);

            unchecked {
                i = i + 1;
            }
        }
    }

    /// @dev Helper function to get the pending payment for an account
    /// @param account the account to get the pending payment for
    /// @param totalReceived the total amount received
    /// @param alreadyReleased the amount already released
    function _pendingPayment(
        address account,
        uint256 totalReceived,
        uint256 alreadyReleased
    )
        internal
        view
        returns (uint256)
    {
        return (totalReceived * _shares[account]) / _totalShares - alreadyReleased;
    }

    /// @dev Add a payee
    /// @param account the account to add as a payee
    /// @param shares_ the amount of shares for the payee
    function _addPayee(address account, uint256 shares_) private {
        if (account == address(0)) {
            revert AccountIsZeroAddress();
        }

        if (shares_ == 0) {
            revert SharesAreZero();
        }

        if (_shares[account] != 0) {
            revert AccountAlreadyHasShares();
        }

        _payees.push(account);
        _shares[account] = shares_;
        _totalShares = _totalShares + shares_;
        emit PayeeAdded(account, shares_);
    }
}

// File: contracts/token/CoinGenieERC20.sol



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

/*
            ██████                                                                                  
           ████████         █████████     ██████████     ███  ████         ███                      
            ██████        █████████████ ██████████████   ████ ██████      ████                      
              ██        ████████  ████ ██████    ██████  ████ ███████     ████                      
              ██       █████          █████        █████ ████ █████████   ████                      
              ██       █████          ████         █████ ████ ████ ██████ ████                      
             ████      █████          ████         █████ ████ ████  ██████████                      
            █████       █████         █████        █████ ████ ████    ████████                      
           ████████      █████████████ ████████████████  ████ ████     ███████                      
          ████  ████      █████████████  ████████████    ████ ████       █████                      
        █████    █████        █████          ████                                                   
      ██████      ██████                                                                            
    ██████         ███████                                                                          
  ████████          ████████           ███████████  █████████████████        ████  ████ ████████████
 ████████           █████████        █████████████  ███████████████████      ████ █████ ████████████
█████████           ██████████     ███████          █████        ████████    ████ █████ ████        
██████████         ████████████    █████            █████        █████████   ████ █████ ████        
██████████████   ██████████████    █████   ████████ ████████████ ████ ██████ ████ █████ ███████████ 
███████████████████████████████    █████   ████████ ██████████   ████  ██████████ █████ ██████████  
███████████████████████████████    ██████      ████ █████        ████    ████████ █████ ████        
 █████████████████████████████      ███████████████ ████████████ ████      ██████ █████ ████████████
  ██████████████████████████          █████████████ █████████████████       █████ █████ ████████████
 */

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import { IUniswapV2Factory } from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import { IUniswapV2Router02 } from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import { IUniswapV2Pair } from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";

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

/**
 * @title CoinGenieERC20
 * @author @neuro_0x
 * @notice A robust and secure ERC20 token for the Coin Genie ecosystem. Inspired by APEX & TokenTool by Bitbond
 * @dev This ERC20 should only be deployed via the launchToken function of the CoinGenie contract.
 */
contract CoinGenieERC20 is ICoinGenieERC20, Ownable, ReentrancyGuard {
    using SafeERC20 for ICoinGenieERC20;

    /// @dev The fee recipients for the contract
    struct FeeTakers {
        address payable feeRecipient;
        address payable coinGenie;
        address payable affiliateFeeRecipient;
    }

    /// @dev The fee percentages for the contract
    struct FeePercentages {
        uint256 taxPercent;
        uint256 maxBuyPercent;
        uint256 maxWalletPercent;
        uint256 discountFeeRequiredAmount;
        uint256 discountPercent;
        uint256 coinGenieFeePercent;
    }

    /// @dev The decimals for the contract
    uint8 private constant _DECIMALS = 18;
    /// @dev The max basis points
    uint256 private constant _MAX_BPS = 10_000;
    /// @dev The max tax that can be set
    uint256 private constant _MAX_TAX = 500; // 5%
    /// @dev The min amount of eth required to open trading
    uint256 private constant _MIN_LIQUIDITY_ETH = 0.5 ether;
    /// @dev The min amount of this token required to open trading
    uint256 private constant _MIN_LIQUIDITY_TOKEN = 1 ether;
    /// @dev The platform liquidity addition fee
    uint256 private constant _LP_ETH_FEE_PERCENTAGE = 100; // 1%
    /// @dev The platform liquidity addition fee
    uint256 private constant _MIN_WALLET_PERCENT = 100; // 1%
    /// @dev The eth autoswap amount
    uint256 private constant _ETH_AUTOSWAP_AMOUNT = 0.025 ether;

    /// @dev The address of the Uniswap V2 Router
    IUniswapV2Router02 private constant _UNISWAP_V2_ROUTER =
        IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);

    /// @dev Mapping of holders and their balances
    mapping(address holder => uint256 balance) private _balances;
    /// @dev Mapping of holders and their allowances
    mapping(address holder => mapping(address spender => uint256 allowance)) private _allowances;
    /// @dev Mapping of holders and their whitelist status
    mapping(address holder => bool isWhiteListed) private _whitelist;
    /// @dev Mapping of fee recipients and the amount of eth they have received
    mapping(address feeRecipient => uint256 amountEthReceived) private _ethReceived;

    /// @dev The fee recipients for the contract
    FeeTakers private _feeTakers;
    /// @dev The fee percentages for the contract
    FeePercentages private _feeAmounts;

    /// @dev The $GENIE contract
    CoinGenieERC20 private _genie;

    /// @dev The address of the Uniswap V2 Pair
    address private _uniswapV2Pair;

    /// @dev The coin genie fee is set
    bool private _isFeeSet;
    /// @dev The trading status of the contract
    bool private _isTradingOpen;
    /// @dev The current swap status of the contract, used for reentrancy checks
    bool private _inSwap;
    /// @dev The swap status of the contract
    bool private _isSwapEnabled;

    /// @dev The name of the token
    string private _name;
    /// @dev The symbol of the token
    string private _symbol;
    /// @dev The total supply of the token
    uint256 private _totalSupply;

    /// @dev Prevents a reentrant call when trying to swap fees
    modifier lockTheSwap() {
        _inSwap = true;
        _;
        _inSwap = false;
    }

    /// @param name_ - the name of the token
    /// @param symbol_ - the ticker symbol of the token
    /// @param totalSupply_ - the totalSupply of the token
    /// @param feeRecipient_ - the address that will be the owner of the token and receive fees
    /// @param coinGenie_ - the address of the Coin Genie
    /// @param affiliateFeeRecipient_ - the address to receive the affiliate fee
    /// @param taxPercent_ - the percent in basis points to use as a tax
    /// @param maxBuyPercent_ - amount of tokens allowed to be transferred in one tx as a percent of the total supply
    /// @param maxWalletPercent_ - amount of tokens allowed to be held in one wallet as a percent of the total supply
    /// @param discountFeeRequiredAmount_ - the amount of tokens required to pay the discount fee
    /// @param discountPercent_ - the percent in basis points to use as a discount
    constructor(
        string memory name_,
        string memory symbol_,
        uint256 totalSupply_,
        address payable feeRecipient_,
        address payable coinGenie_,
        address payable affiliateFeeRecipient_,
        uint256 taxPercent_,
        uint256 maxBuyPercent_,
        uint256 maxWalletPercent_,
        uint256 discountFeeRequiredAmount_,
        uint256 discountPercent_
    )
        payable
    {
        _setERC20Properties(name_, symbol_, totalSupply_);
        _setFeeRecipients(feeRecipient_, coinGenie_, affiliateFeeRecipient_);
        _setFeePercentages(taxPercent_, maxBuyPercent_, maxWalletPercent_, discountFeeRequiredAmount_, discountPercent_);
        _setWhitelist(feeRecipient_, coinGenie_, affiliateFeeRecipient_);

        _balances[feeRecipient_] = totalSupply_;
        emit Transfer(address(0), msg.sender, totalSupply_);
    }

    /////////////////////////////////////////////////////////////////
    //                     Public/External                         //
    /////////////////////////////////////////////////////////////////

    // solhint-disable-next-line no-empty-blocks
    receive() external payable { }

    /// @dev see ICoinGenieERC20 name()
    function name() public view returns (string memory) {
        return string(abi.encodePacked(_name));
    }

    /// @dev see ICoinGenieERC20 symbol()
    function symbol() public view returns (string memory) {
        return string(abi.encodePacked(_symbol));
    }

    /// @dev see ICoinGenieERC20 decimals()
    function decimals() public pure returns (uint8) {
        return _DECIMALS;
    }

    /// @dev see ICoinGenieERC20 totalSupply()
    function totalSupply() public view override returns (uint256) {
        return _totalSupply;
    }

    /// @dev see ICoinGenieERC20 feeRecipient()
    function feeRecipient() public view returns (address payable) {
        return _feeTakers.feeRecipient;
    }

    /// @dev see ICoinGenieERC20 affiliateFeeRecipient()
    function affiliateFeeRecipient() public view returns (address payable) {
        return _feeTakers.affiliateFeeRecipient;
    }

    /// @dev see ICoinGenieERC20 coinGenie()
    function coinGenie() public view returns (address payable) {
        return _feeTakers.coinGenie;
    }

    /// @dev see ICoinGenieERC20 genie()
    function genie() public view returns (address payable) {
        return payable(address(_genie));
    }

    /// @dev see ICoinGenieERC20 isTradingOpen()
    function isTradingOpen() public view returns (bool) {
        return _isTradingOpen;
    }

    /// @dev see ICoinGenieERC20 isSwapEnabled()
    function isSwapEnabled() public view returns (bool) {
        return _isSwapEnabled;
    }

    /// @dev see ICoinGenieERC20 taxPercent()
    function taxPercent() public view returns (uint256) {
        return _feeAmounts.taxPercent;
    }

    /// @dev see ICoinGenieERC20 maxBuyPercent()
    function maxBuyPercent() public view returns (uint256) {
        return _feeAmounts.maxBuyPercent;
    }

    /// @dev see ICoinGenieERC20 maxWalletPercent()
    function maxWalletPercent() public view returns (uint256) {
        return _feeAmounts.maxWalletPercent;
    }

    /// @dev see ICoinGenieERC20 discountFeeRequiredAmount()
    function discountFeeRequiredAmount() public view returns (uint256) {
        return _feeAmounts.discountFeeRequiredAmount;
    }

    /// @dev see ICoinGenieERC20 discountPercent()
    function discountPercent() public view returns (uint256) {
        return _feeAmounts.discountPercent;
    }

    /// @dev see ICoinGenieERC20 lpToken()
    function lpToken() public view returns (address) {
        return _uniswapV2Pair;
    }

    /// @dev see ICoinGenieERC20 balanceOf()
    function amountEthReceived(address feeRecipient_) public view returns (uint256) {
        return _ethReceived[feeRecipient_];
    }

    /// @dev see ICoinGenieERC20 balanceOf()
    function balanceOf(address account) public view override returns (uint256) {
        return _balances[account];
    }

    /// @dev see ICoinGenieERC20 burn()
    function burn(uint256 amount) external {
        _burn(msg.sender, amount);
    }

    /// @dev see ICoinGenieERC20 transfer()
    function transfer(address recipient, uint256 amount) public override returns (bool) {
        _transfer(_msgSender(), recipient, amount);
        return true;
    }

    /// @dev see ICoinGenieERC20 allowance()
    function allowance(address owner, address spender) public view override returns (uint256) {
        return _allowances[owner][spender];
    }

    /// @dev see ICoinGenieERC20 approve()
    function approve(address spender, uint256 amount) public override returns (bool) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    /// @dev see ICoinGenieERC20 transferFrom()
    function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
        _transfer(sender, recipient, amount);
        _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount);

        return true;
    }

    /// @dev see ICoinGenieERC20 manualSwap()
    function manualSwap(uint256 amount) external {
        if (msg.sender != _feeTakers.feeRecipient) {
            revert Unauthorized();
        }

        uint256 contractTokenBalance = _balances[address(this)];
        if (amount > contractTokenBalance) {
            revert InsufficientTokens(amount, contractTokenBalance);
        }

        _swapTokensForEth(amount);

        uint256 contractEthBalance = address(this).balance;
        if (contractEthBalance != 0) {
            _sendEthToFee(contractEthBalance);
        }
    }

    /// @dev see ICoinGenieERC20 createPairAndAddLiquidity()
    function createPairAndAddLiquidity(
        uint256 amountToLP,
        bool payInGenie
    )
        external
        payable
        onlyOwner
        nonReentrant
        returns (address)
    {
        uint256 value = msg.value;
        address from = _msgSender();
        _openTradingChecks(amountToLP, value);

        transfer(address(this), amountToLP);
        _approve(address(this), address(_UNISWAP_V2_ROUTER), _totalSupply);

        uint256 ethAmountToTreasury = (value * _LP_ETH_FEE_PERCENTAGE) / _MAX_BPS;
        if (payInGenie) {
            ethAmountToTreasury = (ethAmountToTreasury * _feeAmounts.discountPercent) / _MAX_BPS;
            ICoinGenieERC20(_genie).safeTransferFrom(from, _feeTakers.coinGenie, _feeAmounts.discountFeeRequiredAmount);
        }

        uint256 ethAmountToLP = value - ethAmountToTreasury;
        _uniswapV2Pair =
            IUniswapV2Factory(_UNISWAP_V2_ROUTER.factory()).createPair(address(this), _UNISWAP_V2_ROUTER.WETH());

        _UNISWAP_V2_ROUTER.addLiquidityETH{ value: ethAmountToLP }(
            address(this), balanceOf(address(this)), 0, 0, from, block.timestamp
        );

        SafeERC20.safeIncreaseAllowance(ICoinGenieERC20(_uniswapV2Pair), address(_UNISWAP_V2_ROUTER), amountToLP);

        _isSwapEnabled = true;
        _isTradingOpen = true;

        if (ethAmountToTreasury != 0) {
            (bool success,) = _feeTakers.coinGenie.call{ value: ethAmountToTreasury }("");
            if (!success) {
                revert TransferFailed(ethAmountToTreasury, address(this), _feeTakers.coinGenie);
            }
        }

        emit TradingOpened(_uniswapV2Pair);

        return _uniswapV2Pair;
    }

    /// @dev see ICoinGenieERC20 addLiquidity()
    function addLiquidity(uint256 amountToLP, bool payInGenie) external payable nonReentrant {
        uint256 value = msg.value;
        address from = _msgSender();
        _addLiquidityChecks(amountToLP, value, from);

        uint256 currentContractBalance = _balances[address(this)];
        transfer(address(this), amountToLP);
        _approve(address(this), address(_UNISWAP_V2_ROUTER), amountToLP);

        uint256 ethAmountToTreasury = (value * _LP_ETH_FEE_PERCENTAGE) / _MAX_BPS;
        if (payInGenie) {
            ethAmountToTreasury = (ethAmountToTreasury * _feeAmounts.discountPercent) / _MAX_BPS;
            ICoinGenieERC20(_genie).safeTransferFrom(from, _feeTakers.coinGenie, _feeAmounts.discountFeeRequiredAmount);
        }

        uint256 ethAmountToLP = value - ethAmountToTreasury;
        SafeERC20.safeIncreaseAllowance(ICoinGenieERC20(_uniswapV2Pair), address(_UNISWAP_V2_ROUTER), amountToLP);
        _UNISWAP_V2_ROUTER.addLiquidityETH{ value: ethAmountToLP }(
            address(this), amountToLP, 0, 0, from, block.timestamp
        );

        if (ethAmountToTreasury != 0) {
            (bool success,) = _feeTakers.coinGenie.call{ value: ethAmountToTreasury }("");
            if (!success) {
                revert TransferFailed(ethAmountToTreasury, address(this), _feeTakers.coinGenie);
            }
        }

        // If there is any eth left in the contract, send it to the fee recipient
        uint256 ethToRefund = address(this).balance;
        if (ethToRefund != 0) {
            _sendEthToFee(ethToRefund);
        }

        // If there is any token left in the contract, send it to the fee recipient
        uint256 newContractBalance = _balances[address(this)];
        if (currentContractBalance < newContractBalance) {
            _transfer(address(this), _feeTakers.feeRecipient, newContractBalance - currentContractBalance);
        }
    }

    /// @dev see ICoinGenieERC20 removeLiquidity()
    function removeLiquidity(uint256 amountToRemove) external nonReentrant {
        address from = _msgSender();
        ICoinGenieERC20(_uniswapV2Pair).safeTransferFrom(from, address(this), amountToRemove);
        _UNISWAP_V2_ROUTER.removeLiquidityETHSupportingFeeOnTransferTokens(
            address(this), amountToRemove, 0, 0, from, block.timestamp
        );
    }

    /// @dev see ICoinGenieERC20 setGenie()
    function setGenie(address genie_) external {
        if (address(_genie) != address(0)) {
            revert GenieAlreadySet();
        }

        _genie = CoinGenieERC20(payable(genie_));
        emit GenieSet(genie_);
    }

    /// @dev see ICoinGenieERC20 setMaxBuyPercent()
    function setMaxBuyPercent(uint256 maxBuyPercent_) external onlyOwner {
        if (maxBuyPercent_ > _MAX_BPS) {
            revert InvalidMaxBuyPercent(maxBuyPercent_);
        }

        _feeAmounts.maxBuyPercent = maxBuyPercent_;
        emit MaxBuyPercentSet(maxBuyPercent_);
    }

    /// @dev see ICoinGenieERC20 setMaxWalletPercent()
    function setMaxWalletPercent(uint256 maxWalletPercent_) external onlyOwner {
        if (maxWalletPercent_ > _MAX_BPS || maxWalletPercent_ < _MIN_WALLET_PERCENT) {
            revert InvalidMaxWalletPercent(maxWalletPercent_);
        }

        _feeAmounts.maxWalletPercent = maxWalletPercent_;
        emit MaxWalletPercentSet(maxWalletPercent_);
    }

    /// @dev see ICoinGenieERC20 setFeeRecipient()
    function setFeeRecipient(address payable feeRecipient_) external onlyOwner {
        _feeTakers.feeRecipient = feeRecipient_;
        transferOwnership(feeRecipient_);
        emit FeeRecipientSet(feeRecipient_);
    }

    /// @dev see ICoinGenieERC20 setCoinGenieFeePercent()
    function setCoinGenieFeePercent(uint256 coinGenieFeePercent_) external onlyOwner {
        if (coinGenieFeePercent_ > _MAX_BPS) {
            revert InvalidCoinGenieFeePercent();
        }

        if (_isFeeSet) {
            revert CoinGenieFeePercentAlreadySet();
        }

        _isFeeSet = true;
        _feeAmounts.coinGenieFeePercent = coinGenieFeePercent_;
    }

    /////////////////////////////////////////////////////////////////
    //                     Private/Internal                        //
    /////////////////////////////////////////////////////////////////

    /// @notice Approves a given amount for the spender.
    /// @dev This is a private function to encapsulate the logic for approvals.
    /// @param owner The address of the token holder.
    /// @param spender The address of the spender.
    /// @param amount The amount of tokens to approve.
    function _approve(address owner, address spender, uint256 amount) private {
        if (owner == address(0) || spender == address(0)) {
            revert ApproveFromZeroAddress();
        }

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

    /// @notice Handles the internal transfer of tokens, applying fees and taxes as needed.
    /// @dev This function implements restrictions and special cases for transfers.
    /// @param from The address sending the tokens.
    /// @param to The address receiving the tokens.
    /// @param amount The amount of tokens to transfer.
    function _transfer(address from, address to, uint256 amount) private {
        _checkTransferRestrictions(from, to, amount);

        uint256 totalTaxAmount;
        if (!_whitelist[from] && !_whitelist[to]) {
            if (from == _uniswapV2Pair && to != address(_UNISWAP_V2_ROUTER)) {
                uint256 maxBuyAmount = (_feeAmounts.maxBuyPercent * _totalSupply) / _MAX_BPS;
                if (amount > maxBuyAmount) {
                    revert ExceedsMaxAmount(amount, maxBuyAmount);
                }

                uint256 maxWalletAmount = (_feeAmounts.maxWalletPercent * _totalSupply) / _MAX_BPS;
                if (_balances[to] + amount > maxWalletAmount) {
                    revert ExceedsMaxAmount(_balances[to] + amount, maxWalletAmount);
                }
            }

            uint256 contractTokenBalance = _balances[address(this)];
            totalTaxAmount =
                (amount * _feeAmounts.taxPercent) / _MAX_BPS + (amount * _feeAmounts.coinGenieFeePercent) / _MAX_BPS;
            if (!_inSwap && to == _uniswapV2Pair && _isTradingOpen && contractTokenBalance >= 0) {
                _swapTokensForEth(_min(amount, contractTokenBalance));

                uint256 contractEthBalance = address(this).balance;
                if (contractEthBalance >= _ETH_AUTOSWAP_AMOUNT) {
                    _sendEthToFee(contractEthBalance);
                }
            }
        }

        if (totalTaxAmount != 0) {
            _balances[address(this)] += totalTaxAmount;
            emit Transfer(from, address(this), totalTaxAmount);
        }

        uint256 amountAfterTax = amount - totalTaxAmount;
        _balances[from] -= amount;
        _balances[to] += amountAfterTax;
        emit Transfer(from, to, amountAfterTax);
    }

    /// @notice Burns a given amount of tokens from the specified address.
    /// @dev Tokens are permanently removed from circulation.
    /// @param from The address from which tokens will be burned.
    /// @param amount The amount of tokens to burn.
    function _burn(address from, uint256 amount) private {
        if (from == address(0)) {
            revert BurnFromZeroAddress();
        }

        uint256 balanceOfFrom = _balances[from];
        if (amount > balanceOfFrom) {
            revert InsufficientTokens(amount, balanceOfFrom);
        }

        unchecked {
            _balances[from] -= amount;
            _totalSupply -= amount;
        }

        emit Transfer(from, address(0), amount);
    }

    /// @notice Conducts checks for adding liquidity.
    /// @dev Used to enforce trading conditions and limits.
    /// @param amountToLP The amount of tokens intended for liquidity.
    /// @param value The amount of ETH provided for liquidity.
    /// @param from The address providing the liquidity.
    function _addLiquidityChecks(uint256 amountToLP, uint256 value, address from) private view {
        if (!_isSwapEnabled || !_isTradingOpen) {
            revert TradingNotOpen();
        }

        if (_balances[from] < amountToLP) {
            revert InsufficientTokens(amountToLP, _MIN_LIQUIDITY_TOKEN);
        }

        if (value < _MIN_LIQUIDITY_ETH) {
            revert InsufficientETH(value, _MIN_LIQUIDITY_ETH);
        }
    }

    /// @notice Checks conditions before opening trading.
    /// @dev Enforces initial liquidity requirements.
    /// @param amountToLP The amount of tokens intended for liquidity.
    /// @param value The amount of ETH provided for liquidity.
    function _openTradingChecks(uint256 amountToLP, uint256 value) private view {
        if (_isSwapEnabled || _isTradingOpen) {
            revert TradingAlreadyOpen();
        }

        if (amountToLP < _MIN_LIQUIDITY_TOKEN || _balances[owner()] < amountToLP) {
            revert InsufficientTokens(amountToLP, _MIN_LIQUIDITY_TOKEN);
        }

        if (value < _MIN_LIQUIDITY_ETH) {
            revert InsufficientETH(value, _MIN_LIQUIDITY_ETH);
        }
    }

    /// @notice Validates the addresses and amounts for transfers.
    /// @dev Throws errors for zero addresses or zero amounts.
    /// @param from The address sending the tokens.
    /// @param to The address receiving the tokens.
    /// @param amount The amount of tokens to transfer.
    function _checkTransferRestrictions(address from, address to, uint256 amount) private pure {
        if (from == address(0) || to == address(0)) {
            revert TransferFromZeroAddress();
        }

        if (amount == 0) {
            revert InsufficientTokens(amount, 0);
        }
    }

    /// @notice Swaps tokens for Ether.
    /// @dev Utilizes Uniswap for the token-to-ETH swap.
    /// @param tokenAmount The amount of tokens to swap for ETH.
    function _swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
        address[] memory path = new address[](2);
        path[0] = address(this);
        path[1] = _UNISWAP_V2_ROUTER.WETH();
        _approve(address(this), address(_UNISWAP_V2_ROUTER), tokenAmount);
        _UNISWAP_V2_ROUTER.swapExactTokensForETHSupportingFeeOnTransferTokens(
            tokenAmount, 0, path, address(this), block.timestamp
        );
    }

    /// @notice Distributes Ether to the specified fee recipients.
    /// @dev Divides and sends Ether based on predefined fee ratios.
    /// @param amount The total amount of Ether to distribute.
    function _sendEthToFee(uint256 amount) private {
        uint256 tax = _feeAmounts.taxPercent;
        uint256 feeRecipientShare = (amount * tax) / (tax + _feeAmounts.coinGenieFeePercent);
        uint256 coinGenieShare = amount - feeRecipientShare;

        address payable _coinGenie = _feeTakers.coinGenie;
        (bool successCoinGenie,) = _coinGenie.call{ value: coinGenieShare }("");
        if (!successCoinGenie) {
            revert TransferFailed(coinGenieShare, address(this), _coinGenie);
        }

        address payable _feeRecipient = _feeTakers.feeRecipient;
        (bool successFeeRecipient,) = _feeRecipient.call{ value: feeRecipientShare }("");
        _ethReceived[_feeRecipient] += feeRecipientShare;
        if (!successFeeRecipient) {
            revert TransferFailed(feeRecipientShare, address(this), _feeTakers.coinGenie);
        }

        emit EthSentToFee(feeRecipientShare, coinGenieShare);
    }

    /// @notice Returns the smaller of the two provided values.
    /// @param a First number.
    /// @param b Second number.
    /// @return The smaller value between a and b.
    function _min(uint256 a, uint256 b) private pure returns (uint256) {
        return a < b ? a : b;
    }

    /// @notice Sets the properties for the ERC20 token.
    /// @dev Initializes the token's name, symbol, and total supply.
    /// @param name_ The name of the token.
    /// @param symbol_ The symbol of the token.
    /// @param totalSupply_ The total supply of the token.
    function _setERC20Properties(string memory name_, string memory symbol_, uint256 totalSupply_) private {
        _name = name_;
        _symbol = symbol_;

        if (totalSupply_ < 1 ether || totalSupply_ > 100_000_000_000 ether) {
            revert InvalidTotalSupply(totalSupply_);
        }
        _totalSupply = totalSupply_;
    }

    /// @notice Assigns addresses for fee recipients.
    /// @dev Sets addresses for the main fee recipient, Coin Genie, and affiliate fee recipient.
    /// @param feeRecipient_ The address of the main fee recipient.
    /// @param coinGenie_ The address for Coin Genie.
    /// @param affiliateFeeRecipient_ The address for the affiliate fee recipient.
    function _setFeeRecipients(
        address payable feeRecipient_,
        address payable coinGenie_,
        address payable affiliateFeeRecipient_
    )
        private
    {
        _feeTakers.feeRecipient = feeRecipient_;
        _feeTakers.coinGenie = coinGenie_;

        if (affiliateFeeRecipient_ == address(0)) {
            _feeTakers.affiliateFeeRecipient = coinGenie_;
        } else {
            _feeTakers.affiliateFeeRecipient = affiliateFeeRecipient_;
        }
    }

    /// @notice Configures fee percentages and related parameters.
    /// @dev Sets the tax percentage, max buy percentage, and other fee-related parameters.
    /// @param taxPercent_ The tax percentage on transactions.
    /// @param maxBuyPercent_ The maximum buy percentage.
    /// @param maxWalletPercent_ The maximum wallet percentage.
    /// @param discountFeeRequiredAmount_ The discount fee required amount.
    /// @param discountPercent_ The discount percentage.
    function _setFeePercentages(
        uint256 taxPercent_,
        uint256 maxBuyPercent_,
        uint256 maxWalletPercent_,
        uint256 discountFeeRequiredAmount_,
        uint256 discountPercent_
    )
        private
    {
        _feeAmounts.taxPercent = taxPercent_;
        _feeAmounts.maxBuyPercent = maxBuyPercent_;
        _feeAmounts.maxWalletPercent = maxWalletPercent_;
        _feeAmounts.discountFeeRequiredAmount = discountFeeRequiredAmount_;
        _feeAmounts.discountPercent = discountPercent_;
    }

    /// @notice Whitelists specified addresses.
    /// @dev Adds provided addresses to the whitelist.
    /// @param feeRecipient_ The address of the main fee recipient.
    /// @param coinGenie_ The address for Coin Genie.
    /// @param affiliateFeeRecipient_ The address for the affiliate fee recipient.
    function _setWhitelist(address feeRecipient_, address coinGenie_, address affiliateFeeRecipient_) private {
        _whitelist[feeRecipient_] = true;
        _whitelist[coinGenie_] = true;
        _whitelist[affiliateFeeRecipient_] = true;
        _whitelist[address(this)] = true;
    }
}

// File: contracts/token/ICoinGenieERC20.sol



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

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

/**
 * @title ICoinGenieERC20
 * @author @neuro_0x
 * @dev Interface for the CoinGenie ERC20 token
 */
interface ICoinGenieERC20 is IERC20 {
    /////////////////////////////////////////////////////////////////
    //                           Events                            //
    /////////////////////////////////////////////////////////////////

    /// @dev Emits when Genie is set
    /// @param genie - the address of the $GENIE contract
    event GenieSet(address indexed genie);

    /// @dev Emits when trading is opened
    /// @param pair - the address of the Uniswap V2 Pair
    event TradingOpened(address indexed pair);

    /// @dev Emits when the max buy percent is set
    /// @param maxBuyPercent - the max buy percent
    event MaxBuyPercentSet(uint256 indexed maxBuyPercent);

    /// @dev Emits when the fee recipient is set
    /// @param feeRecipient - the address of the fee recipient
    event FeeRecipientSet(address indexed feeRecipient);

    /// @dev Emits when the max wallet percent is set
    /// @param maxWalletPercent - the max wallet percent
    event MaxWalletPercentSet(uint256 indexed maxWalletPercent);

    /// @dev Emits when eth is sent to the fee recipients
    /// @param feeRecipientShare - the amount of eth sent to the fee recipient as a share
    /// @param coinGenieShare - the amount of eth sent to the coin genie as a share
    event EthSentToFee(uint256 indexed feeRecipientShare, uint256 indexed coinGenieShare);

    /////////////////////////////////////////////////////////////////
    //                           Errors                            //
    /////////////////////////////////////////////////////////////////

    /// @dev Reverts when the caller is not authorized to perform an action
    error Unauthorized();

    /// @dev Reverts when trading is not open
    error TradingNotOpen();

    /// @dev Reverts when Genie is already set
    error GenieAlreadySet();

    /// @dev Reverts when trading is already open
    error TradingAlreadyOpen();

    /// @dev Reverts when trying to burn from the zero address
    error BurnFromZeroAddress();

    /// @dev Reverts when trying to approve from the zero address
    error ApproveFromZeroAddress();

    /// @dev Reverts when trying to transfer from the zero address
    error TransferFromZeroAddress();

    /// @dev Reverts when coin genie fee is already set
    error CoinGenieFeePercentAlreadySet();

    /// @dev Reverts when invalid coin genie fee percent
    error InvalidCoinGenieFeePercent();

    /// @dev Reverts when invalid total supply
    /// @param totalSupply - the total supply
    error InvalidTotalSupply(uint256 totalSupply);

    /// @dev Reverts when trying to set an invalid max wallet percent
    /// @param maxWalletPercent - the max wallet percent
    error InvalidMaxWalletPercent(uint256 maxWalletPercent);

    /// @dev Reverts when trying to set an invalid max buy percent
    /// @param maxBuyPercent - the max buy percent
    error InvalidMaxBuyPercent(uint256 maxBuyPercent);

    /// @dev Reverts when there is not enough eth send in the tx
    /// @param amount - the amount of eth sent
    /// @param minAmount - the min amount of eth required
    error InsufficientETH(uint256 amount, uint256 minAmount);

    /// @dev Reverts when the amount sent is beyond the max amount allowed
    /// @param amount - the amount sent
    /// @param maxAmount - the max amount allowed
    error ExceedsMaxAmount(uint256 amount, uint256 maxAmount);

    /// @dev Reverts when there are not enough tokens to perform the action
    /// @param amount - the amount of tokens sent
    /// @param minAmount - the min amount of tokens required
    error InsufficientTokens(uint256 amount, uint256 minAmount);

    /// @dev Reverts when there is not enough allowance to perform the action
    /// @param amount - the amount of tokens sent
    /// @param allowance - the amount of allowance required
    error InsufficientAllowance(uint256 amount, uint256 allowance);

    /// @dev Reverts when there is an error when transferring
    /// @param amount - the amount sent
    /// @param from - the address the transfer is from
    /// @param to - the address the transfer is to
    error TransferFailed(uint256 amount, address from, address to);

    /////////////////////////////////////////////////////////////////
    //                       Public/External                       //
    /////////////////////////////////////////////////////////////////

    /// @dev Gets the name of the token
    /// @return the name of the token
    function name() external view returns (string memory);

    /// @dev Gets the symbol of the token
    /// @return the symbol of the token
    function symbol() external view returns (string memory);

    /// @dev Gets the number of decimals the token uses
    /// @return the number of decimals the token uses
    function decimals() external pure returns (uint8);

    /// @dev Gets the total supply of the token
    /// @return the total supply of the token
    function totalSupply() external view returns (uint256);

    /// @dev Gets the address of the fee recipient
    /// @return the address of the fee recipient
    function feeRecipient() external view returns (address payable);

    /// @dev Gets the address of the CoinGenie contract
    /// @return the address of the CoinGenie contract
    function coinGenie() external view returns (address payable);

    /// @dev Gets the address of the $GENIE contract
    /// @return the address of the $GENIE contract
    function genie() external view returns (address payable);

    /// @dev Gets the address of the affiliate fee recipient
    /// @return the address of the affiliate fee recipient
    function affiliateFeeRecipient() external view returns (address payable);

    /// @dev Gets the trading status of the token
    /// @return the trading status of the token
    function isTradingOpen() external view returns (bool);

    /// @dev Gets the trading status of the token
    /// @return the trading status of the token
    function isSwapEnabled() external view returns (bool);

    /// @dev Gets the tax percent
    /// @return the tax percent
    function taxPercent() external view returns (uint256);

    /// @dev Gets the max buy percent
    /// @return the max buy percent
    function maxBuyPercent() external view returns (uint256);

    /// @dev Gets the max wallet percent
    /// @return the max wallet percent
    function maxWalletPercent() external view returns (uint256);

    /// @dev Gets the discount fee required amount in $GENIE
    /// @return the discount fee required amount in $GENIE
    function discountFeeRequiredAmount() external view returns (uint256);

    /// @dev Gets the discount percent received if paying in $GENIE
    /// @return the discount percent received if paying in $GENIE
    function discountPercent() external view returns (uint256);

    /// @dev Gets the Uniswap V2 pair address
    /// @return the uniswap v2 pair address
    function lpToken() external view returns (address);

    /// @dev Gets the balance of the specified address
    /// @param account - the address to get the balance of
    /// @return the balance of the account
    function balanceOf(address account) external view returns (uint256);

    /// @dev Gets the amount of eth received by the fee recipient
    /// @param feeRecipient_ - the address to get the amount of eth received
    /// @return the amount of eth received
    function amountEthReceived(address feeRecipient_) external view returns (uint256);

    /// @dev Burns `amount` tokens from the caller
    /// @param amount - the amount of tokens to burn
    function burn(uint256 amount) external;

    /// @dev Transfers `amount` tokens to `recipient`
    /// @param recipient - the address to transfer to
    /// @param amount - the amount of tokens to transfer
    /// @return true if the transfer was successful
    function transfer(address recipient, uint256 amount) external returns (bool);

    /// @dev Gets the allowance of an address to spend tokens on behalf of the owner
    /// @param owner - the address to get the allowance of
    /// @param spender - the address to get the allowance for
    /// @return the allowance of the owner for the spender
    function allowance(address owner, address spender) external view returns (uint256);

    /// @dev Approves an address to spend tokens on behalf of the caller
    /// @param spender - the address to approve
    /// @param amount - the amount to approve
    /// @return true if the approval was successful
    function approve(address spender, uint256 amount) external returns (bool);

    /// @dev Transfers tokens from one address to another
    /// @param sender - the address to transfer from
    /// @param recipient - the address to transfer to
    /// @param amount - the amount to transfer
    /// @return true if the transfer was successful
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /// @dev Swaps the contracts tokens for eth
    function manualSwap(uint256 amount) external;

    /// @dev Opens trading by adding liquidity to Uniswap V2
    /// @param amountToLP - the amount of tokens to add liquidity with
    /// @param payInGenie - true if paying with $GENIE
    /// @return the address of the LP Token created
    function createPairAndAddLiquidity(uint256 amountToLP, bool payInGenie) external payable returns (address);

    /// @dev Adds liquidity to Uniswap V2
    /// @param amountToLP - the amount of tokens to add liquidity with
    /// @param payInGenie - true if paying with $GENIE
    function addLiquidity(uint256 amountToLP, bool payInGenie) external payable;

    /// @dev Removes liquidity from Uniswap V2
    /// @param amountToRemove - the amount of LP tokens to remove
    function removeLiquidity(uint256 amountToRemove) external;

    /// @dev Sets the address of the $GENIE contract
    /// @param genie_ - the address of the $GENIE contract
    function setGenie(address genie_) external;

    /// @dev Sets the fee recipient
    /// @param feeRecipient_ - the address of the fee recipient
    function setFeeRecipient(address payable feeRecipient_) external;

    /// @dev Sets the max amount of tokens that can be bought in a tx as a percent of the total supply
    /// @param maxBuyPercent_ - the max buy percent
    function setMaxBuyPercent(uint256 maxBuyPercent_) external;

    /// @dev Sets the max amount of tokens a wallet can hold as a percent of the total supply
    /// @param maxWalletPercent_ - the max wallet percent
    function setMaxWalletPercent(uint256 maxWalletPercent_) external;

    /// @notice Sets the Coin Genie fee percentage.
    /// @param coinGenieFeePercent_ The Coin Genie fee percentage.
    function setCoinGenieFeePercent(uint256 coinGenieFeePercent_) external;
}