// File: src/Control/IOwnableV2.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;


/**
 * @title Ownable
 * 
 * parent for ownable contracts
 */
interface IOwnableV2 {
  event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);

  function owner() external view returns (address);
  function transferOwnership(address newOwner_) external;
}

// File: src/Control/IPausable.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import { IOwnableV2 } from "./IOwnableV2.sol";

interface IPausable is IOwnableV2 {
  function paused() external view returns (bool);
  function setPaused(bool value) external;
}

// File: src/Control/OwnableV2.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import { Context } from "../library/Context.sol";
import { IOwnableV2 } from "./IOwnableV2.sol";

/**
 * @title Ownable
 * 
 * parent for ownable contracts
 */
abstract contract OwnableV2 is IOwnableV2, Context {
  constructor(address owner_) {
    _owner_ = owner_;
    emit OwnershipTransferred(address(0), _owner());
  }

  address internal _owner_;

  function _owner() internal virtual view returns (address) {
    return _owner_;
  }

  function owner() external virtual override view returns (address) {
    return _owner();
  }

  modifier onlyOwner() {
    require(_owner() == _msgSender(), "Only the owner can execute this function");
    _;
  }

  function _transferOwnership(address newOwner_) internal virtual onlyOwner {
    // keep track of old owner for event
    address oldOwner = _owner();

    // set the new owner
    _owner_ = newOwner_;

    // emit event about ownership change
    emit OwnershipTransferred(oldOwner, _owner());
  }

  function transferOwnership(address newOwner_) external virtual override onlyOwner {
    _transferOwnership(newOwner_);
  }
}

// File: src/Control/Pausable.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import { IPausable } from "./IPausable.sol";
import { OwnableV2 } from "./OwnableV2.sol";

abstract contract Pausable is IPausable, OwnableV2 {
  bool internal _paused;

  modifier onlyNotPaused() {
    require(!_paused, "Contract is paused");
    _;
  }

  function paused() external view override returns (bool) {
    return _paused;
  }

  function _setPaused(bool value) internal virtual {
    _paused = value;
  }

  function setPaused(bool value) external override onlyOwner {
    _setPaused(value);
  }
}

// File: src/Fees/FeeCollector.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import { IFeeCollector } from "./IFeeCollector.sol";
import { Address } from "../library/Address.sol";
import { IFees } from "./IFees.sol";
import { OwnableV2 } from "../Control/OwnableV2.sol";

abstract contract FeeCollector is IFeeCollector, OwnableV2 {
  using Address for address payable;

  IFees internal _fees;

  uint256 internal _feePercentDenominator = 10 ** 18;

  modifier takeFee(string memory feeType) {
    bool exempt = _fees.isAddressExemptFromFees(_msgSender());
    require(exempt || _fees.getFeeAmountForType(feeType) == msg.value, "Incorrect fee");
    if (!exempt)
      payable(address(_fees)).sendValue(msg.value);
    _;
  }

  function feesContract() external view override returns (address) {
    return address(_fees);
  }

  function _setFeesContract(address contractAddress) internal virtual {
    _fees = IFees(contractAddress);
  }

  function setFeesContract(address contractAddress) external override onlyOwner {
    _setFeesContract(contractAddress);
  }

  function feePercentDenominator() external view override returns (uint256) {
    return _feePercentDenominator;
  }

  function setFeePercentDenominator(uint256 value) external virtual override onlyOwner {
    _feePercentDenominator = value;
  }

  function _getFeePercentInRange(
    string memory minFeeType,
    string memory maxFeeType,
    uint256 input,
    uint256 percent
  ) internal virtual view returns (uint256) {
    uint256 feeMin = _fees.getFeeAmountForType(minFeeType);
    uint256 feeMax = _fees.getFeeAmountForType(maxFeeType);

    uint256 feeAmount = feeMin;
    feeAmount += (feeMax - feeMin) * percent / _feePercentDenominator;

    return input * feeAmount / _feePercentDenominator;
  }

  function getFeePercentInRange(
    string memory minFeeType,
    string memory maxFeeType,
    uint256 input,
    uint256 percent
  ) external view override returns (uint256) {
    return _getFeePercentInRange(minFeeType, maxFeeType, input, percent);
  }

  function _takeFeePercentInRange(
    string memory minFeeType,
    string memory maxFeeType,
    uint256 amount,
    uint256 percent
  ) internal virtual {
    require(
      _getFeePercentInRange(minFeeType, maxFeeType, amount, percent) == msg.value,
      "Incorrect fee"
    );

    if (!_fees.isAddressExemptFromFees(_msgSender()))
      payable(address(_fees)).sendValue(msg.value);
  }
}

// File: src/Fees/IFeeCollector.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import { IOwnableV2 } from "../Control/IOwnableV2.sol";

interface IFeeCollector is IOwnableV2 {
  function feesContract() external view returns (address);
  function setFeesContract(address contractAddress_) external;
  function feePercentDenominator() external view returns (uint256);
  function setFeePercentDenominator(uint256 value) external;
  function getFeePercentInRange(
    string memory minFeeType,
    string memory maxFeeType,
    uint256 input,
    uint256 percent
  ) external view returns (uint256 output);
}

// File: src/Fees/IFees.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import { IGovernable } from "../Governance/IGovernable.sol";
import { IPausable } from "../Control/IPausable.sol";

interface IFees is IGovernable, IPausable {
  function getFeeAmountForType(string memory feeType) external view returns (uint256);
  function setFeeAmountForType(string memory feeType, uint256 amount) external;
  function setAddressExemptFromFees(address account, bool value) external;
  function isAddressExemptFromFees(address account) external view returns (bool);
  function feesDistributed() external view returns (uint256 total, uint256 treasury, uint256 staking);
  function treasuryFeeAddress() external view returns (address);
  function setTreasuryFeeAddress(address payable value) external;
  function stakingFeeAddress() external view returns (address);
  function setStakingFeeAddress(address payable value) external;
  function getFees() external view returns (uint16 treasuryFee, uint16 stakingFee);
  function setFees(uint16 treasuryFee, uint16 stakingFee) external;
}

// File: src/Governance/Governable.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import { IGovernable } from "./IGovernable.sol";
import { OwnableV2 } from "../Control/OwnableV2.sol";

/**
 * @title Governable
 * 
 * parent for governable contracts
 */
abstract contract Governable is IGovernable, OwnableV2 {
  constructor(address owner_, address governor_) OwnableV2(owner_) {
    _governor_ = governor_;
    emit GovernorshipTransferred(address(0), _governor());
  }

  address internal _governor_;

  function _governor() internal view returns (address) {
    return _governor_;
  }

  function governor() external view override returns (address) {
    return _governor();
  }

  modifier onlyGovernor() {
    require(_governor() == _msgSender(), "Only the governor can execute this function");
    _;
  }

  // not currently used - but here it is in case we want this
  // modifier onlyOwnerOrGovernor() {
  //   require(_owner() == _msgSender() || _governor() == _msgSender(), "Only the owner or governor can execute this function");
  //   _;
  // }

  function _transferGovernorship(address newGovernor) internal virtual {
    // keep track of old owner for event
    address oldGovernor = _governor();

    // set the new owner
    _governor_ = newGovernor;

    // emit event about ownership change
    emit GovernorshipTransferred(oldGovernor, _governor());
  }

  function transferGovernorship(address newGovernor) external override onlyOwner {
    _transferGovernorship(newGovernor);
  }
}

// File: src/Governance/IGovernable.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import { IOwnableV2 } from "../Control/IOwnableV2.sol";

interface IGovernable is IOwnableV2 {
  event GovernorshipTransferred(address indexed oldGovernor, address indexed newGovernor);

  function governor() external view returns (address);
  function transferGovernorship(address newGovernor) external;
}

// File: src/IDCounter.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import { IIDCounter } from "./IIDCounter.sol";

abstract contract IDCounter is IIDCounter {
  uint256 internal _count;

  function count() external view override returns (uint256) {
    return _count;
  }

  function _next() internal virtual returns (uint256) {
    return _count++;
  }
}

// File: src/IIDCounter.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IIDCounter {
  function count() external view returns (uint256);
}

// File: src/Tokens/ITradingTokenFactoryV1.sol



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

interface ITradingTokenFactoryV1 {
  function createToken(
    string memory name_, 
    string memory symbol_, 
    uint8 decimals_,
    uint256 totalSupply_,
    address owner_,
    uint256[] memory tokenData) external returns(address);
}

// File: src/Tokens/ITradingTokenManagerV1.sol



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

import { IGovernable } from "../Governance/IGovernable.sol";
import { IPausable } from "../Control/IPausable.sol";
import { IIDCounter } from "../IIDCounter.sol";
import { IFeeCollector } from "../Fees/IFeeCollector.sol";

interface ITradingTokenManagerV1 is IGovernable, IPausable, IIDCounter, IFeeCollector {
  event CreatedToken(uint40 indexed id, address tokenAddress);

  function factory() external view returns (address);
  function setFactory(address value) external;
  function createToken(
    string memory name_, 
    string memory symbol_, 
    uint8 decimals_,
    uint256 totalSupply_,
    uint256[] memory tokenData
  ) external payable;
  function getTokenDataByAddress(address address_) external view returns (
    address tokenAddress_,
    string memory name_, 
    string memory symbol_, 
    uint8 decimals_,
    uint256 totalSupply_,
    uint256 totalBalance_,
    uint256 launchedAt_,
    address owner_,
    address dexPair_
  );
  function getTokenDataById(uint40 id) external view returns (
    address tokenAddress_,
    string memory name_, 
    string memory symbol_, 
    uint8 decimals_,
    uint256 totalSupply_,
    uint256 totalBalance_,
    uint256 launchedAt_,
    address owner_,
    address dexPair_
  );
}

// File: src/Tokens/ITradingTokenV1.sol



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

interface ITradingTokenV1 {
  event SwapTokensForETH(
    uint256 amountIn,
    address[] path
  );
  function launch() external payable;
  function getTokenData() external view returns (
    string memory name_, 
    string memory symbol_, 
    uint8 decimals_,
    uint256 totalSupply_,
    uint256 totalBalance_,
    uint256 launchedAt,
    address owner_,
    address dexPair
  );
}

// File: src/Tokens/TradingTokenManagerV1..sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import { ITradingTokenManagerV1 } from "./ITradingTokenManagerV1.sol";
import { Address } from "../library/Address.sol";
import { Governable } from "../Governance/Governable.sol";
import { Pausable } from "../Control/Pausable.sol";
import { IDCounter } from "../IDCounter.sol";
import { FeeCollector } from "../Fees/FeeCollector.sol";
import { ITradingTokenV1 } from "./ITradingTokenV1.sol";
import { ITradingTokenFactoryV1 } from "./ITradingTokenFactoryV1.sol";

contract TradingTokenManagerV1 is ITradingTokenManagerV1, Governable, Pausable, IDCounter, FeeCollector {
  using Address for address payable;

  /** @dev set the deployer as both owner and governor initially */
  constructor(address factoryAddress, address feesAddress) Governable(_msgSender(), _msgSender()) {
    _factory = ITradingTokenFactoryV1(factoryAddress);
    _setFeesContract(feesAddress);
  }

  ITradingTokenFactoryV1 internal _factory;

  mapping(uint40 => ITradingTokenV1) private _tokens;
  mapping(address => uint40) private _tokenAddressMap;
  
  function factory() external view override returns (address) {
    return address(_factory);
  }

  function setFactory(address value) external virtual override onlyOwner {
    _factory = ITradingTokenFactoryV1(value);
  }

  function createToken(
    string memory name_, 
    string memory symbol_, 
    uint8 decimals_,
    uint256 totalSupply_,
    uint256[] memory tokenData
  ) external payable virtual override onlyNotPaused takeFee("DeployStandardToken") {
    uint40 id = uint40(_next());

    _tokens[id] = ITradingTokenV1(
      _factory.createToken(
        name_, 
        symbol_, 
        decimals_,
        totalSupply_,
        _msgSender(),
        tokenData
      )
    );

    address tokenAddress = address(_tokens[id]);
    _tokenAddressMap[tokenAddress] = id;
    emit CreatedToken(id, tokenAddress);
  }

  function _getTokenDataById(uint40 id) internal virtual view returns (
    address tokenAddress_,
    string memory name_, 
    string memory symbol_, 
    uint8 decimals_,
    uint256 totalSupply_,
    uint256 totalBalance_,
    uint256 launchedAt_,
    address owner_,
    address dexPair_
  ){
    (
      name_, 
      symbol_, 
      decimals_,
      totalSupply_,
      totalBalance_,
      launchedAt_,
      owner_,
      dexPair_
    ) = _tokens[id].getTokenData();

    tokenAddress_ = address(_tokens[id]);
  }

  function getTokenDataById(uint40 id) external override view returns (
    address tokenAddress_,
    string memory name_, 
    string memory symbol_, 
    uint8 decimals_,
    uint256 totalSupply_,
    uint256 totalBalance_,
    uint256 launchedAt_,
    address owner_,
    address dexPair_
  ){
    return _getTokenDataById(id);
  }

  function getTokenDataByAddress(address address_) external override view returns (
    address tokenAddress_,
    string memory name_, 
    string memory symbol_, 
    uint8 decimals_,
    uint256 totalSupply_,
    uint256 totalBalance_,
    uint256 launchedAt_,
    address owner_,
    address dexPair_
  ){
    return _getTokenDataById(_tokenAddressMap[address_]);
  }

  receive() external payable {}
}

// File: src/library/Address.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)

pragma solidity ^0.8.0;

/**
 * @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
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        assembly {
            size := extcodesize(account)
        }
        return size > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

// File: src/library/Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.3.2 (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;
    }
}