// Contract: FractionalAsset
// Target function: function transferFrom(
 returns (string memory);

    /**
        Returns The Symbol (Ticker) Of A Collection
     */
    function symbol() external view returns (string memory);

    /**
        Returns The Number Of Fractions This NFT Is Split Into
     */
    function numFractions() external view returns (uint256);

    /**
        Initializes The FractionalAsset
     */
    function __init__(
        string[] calldata strings,
        uint256[] calldata values,
        address[] calldata addrs
    ) external;
}

interface IDatabase {
    function isVerified(address account) external view returns (bool);
    function isAuthorized(address account) external view returns (bool);
}

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 *
 * _Available since v3.4._
 */
contract Clones {

    /**
        @dev Deploys and returns the address of a clone of address(this
        Created by DeFi Mark To Allow Clone Contract To Easily Create Clones Of Itself
        Without redundancy
     */
    function clone() external returns(address) {
        return _clone(address(this));
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     */
    function _clone(address implementation) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
            mstore(add(ptr, 0x14), shl(0x60, implementation))
            mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
            instance := create(0, ptr, 0x37)
        }
        require(instance != address(0), "ERC1167: create failed");
    }
}

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) {
        // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
        // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
        // for accounts without code, i.e. `keccak256('')`
        bytes32 codehash;
        bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
        // solhint-disable-next-line no-inline-assembly
        assembly { codehash := extcodehash(account) }
        return (codehash != accountHash && codehash != 0x0);
    }

}

contract FractionalAssetData is Context {

    /**
        Master Database Which Interacts With KYC And Auth Databases
     */
    IDatabase public constant Database = IDatabase(0x238a94E37a1bAde56Cfcc5dbE7f48DA88aa9Db19);

    /**
        Is Initialized
     */
    bool internal initialized;

    /**
        Name For NFT Compatibility
     */
    string internal _name;

    /**
        Symbol For NFT Compatibility
     */
    string internal _symbol;

    /**
        Current Token ID For Tracking Purposes
     */
    uint256 internal _currentTokenID;

    /**
        Mapping From Mint Tokens To Cost
     */
    mapping ( address => uint256 ) public mintCost;

    /**
        Mapping From A TokenID To An Address Which Dictates Ownership Of That Specific ID
     */
    mapping(uint256 => address) internal _owners;

    /**
        List Of Registered Owners Containing At Least 1 Fractional Asset
     */
    address[] internal _registeredOwners;

    /**
        Mapping Between An Owner And Their Index In The `_registeredOwners` List
     */
    mapping( address => uint256 ) internal _ownerIndex;

    /**
        Mapping From Owner Address To The Number Of Fractional Assets They Own In Total
        Ensures NFT Compatibility
     */
    mapping(address => uint256) internal _balances;

    /**
        Mapping from token ID to approved address
     */
    mapping(uint256 => address) internal _tokenApprovals;

    /**
        Mapping from owner to operator approvals
    */
    mapping(address => mapping(address => bool)) internal _operatorApprovals;

    /**
        Returns The URI Of The Images Associated With Each Collection
     */
    string internal baseURI;

    /**
        Number Of Fractions NFT Is Split Into
     */
    uint256 internal nFractions;

    /**
        Whether Or Not Minting Is Enabled
     */
    bool public mintingEnabled;

    /**
        Whether Or Not An Allowlist Is Enabled
     */
    bool public allowlistEnabled;

    /**
        Recipient of Mint Funds
     */
    address public mintRecipient;

    // Mapping from owner to excluded rewards
    mapping(address => uint256) totalExcluded;

    // total dividends for tracking
    uint256 internal dividendsPerNFT;

    // total rewards received
    uint256 public totalRewards;

    // Reward Token
    address public rewardToken;

    // precision value
    uint256 internal constant precision = 10**18;

    // Merkle Root
    bytes32 internal merkleRoot;

    /**
        Ensures `account` is KYC Verified Before Permitting
        Access To Certain Functionality
     */
    modifier isVerified(address account) {
        require(
            account != address(0),
            'Zero Address'
        );
        require(
            Database.isVerified(account),
            'Account Not KYC Verified'
        );
        _;
    }

    /**
        Ensures Caller Is Authorized To Call Restricted Functions
     */
    modifier onlyAuthorized() {
        require(
            Database.isAuthorized(_msgSender()) == true,
            'Not Authorized To Call'
        );
        _;
    }

    /**
        Events To Support Data Tracking
     */
    event BaseURIChange(string oldURI, string newURI);

}


contract FractionalAsset is FractionalAssetData, IFractionalAsset, Clones {

  using Address for address;

  // Event Declarations
event Mint(address indexed to, uint256 indexed tokenId);
event MintingEnabled();
event MintingDisabled();
event AllowlistEnabled();
event AllowlistDisabled();
event MerkleRootSet(bytes32 newRoot);
event Withdrawal(address indexed token, address indexed to, uint256 amount);
event MintCostSet(address indexed token, uint256 newCost);
event RewardsDeposited(uint256 amount);
event RewardsClaimed(address indexed user, uint256 amount);

  /**
      Initializes The FractionalAsset
   */
  function __init__(
      string[] calldata strings,
      uint256[] calldata values,
      address[] calldata addrs
  ) external override {
      require(
          !initialized,
          'Already Initialized'
      );
      initialized = true;
      _name = strings[0];
      _symbol = strings[1];
      baseURI = strings[2];
      nFractions = values[0];
      for (uint i = 0; i < values[1]; i++) {
          mintCost[addrs[i]] = values[2 + i];
      }
      rewardToken = addrs[values[1]];
      mintRecipient = addrs[values[1] + 1];
  }
  
  /**
      Sets The Base URI, Updating Images For ALL Collections
   */
  function setBaseURI(string calldata newURI) external onlyAuthorized {
      emit BaseURIChange(baseURI, newURI);
      baseURI = newURI;
  }

  function enableMinting() external onlyAuthorized {
      mintingEnabled = true;
      emit MintingEnabled();
  }

  function setMintRecipient(address newRecipient) external onlyAuthorized {
      mintRecipient = newRecipient;
  }

  function disableMinting() external onlyAuthorized {
      mintingEnabled = false;
      emit MintingDisabled();
  }

  function enableAllowlist() external onlyAuthorized {
      allowlistEnabled = true;
      emit AllowlistEnabled();
  }

  function disableAllowlist() external onlyAuthorized {
      allowlistEnabled = false;
      emit AllowlistDisabled();
  }

  function setMerkleRoot(bytes32 root) external onlyAuthorized {
      merkleRoot = root;
      emit MerkleRootSet(root);
  }

  function withdrawETH(address to) external onlyAuthorized {
      (bool s,) = payable(to).call{value: address(this).balance}("");
      require(s);
      emit Withdrawal(address(0), to, address(this).balance);
  }

  function withdrawToken(address token, address to) external onlyAuthorized {
      IERC20(token).transfer(to, IERC20(token).balanceOf(address(this)));
      emit Withdrawal(token, to, IERC20(token).balanceOf(address(this)));
  }

  function setCost(address mintToken, uint256 newCost) external onlyAuthorized {
      mintCost[mintToken] = newCost;
      emit MintCostSet(mintToken, newCost);
  }

  function ownerMint(address to, uint256 num) external onlyAuthorized {
      for (uint i = 0; i < num;) {
          _safeMint(to, _currentTokenID);
          unchecked { ++i; }
      }
  }

  function batchClaim(address[] calldata users) external onlyAuthorized {
      uint len = users.length;
      for (uint i = 0; i < len;) {
          _claimRewards(users[i]);
          unchecked { ++i; }
      }
  }

  function depositRewards(uint256 amount) external onlyAuthorized {
      require(
          _currentTokenID > 0,
          'Zero Tokens'
      );
      require(
          IERC20(rewardToken).allowance(msg.sender, address(this)) >= amount,
          'Insufficient Allowance'
      );
      require(
          IERC20(rewardToken).balanceOf(msg.sender) >= amount,
          'Insufficient Balance'
      );
      require(
          IERC20(rewardToken).transferFrom(msg.sender, address(this), amount),
          'Error TransferFrom'
      );
      unchecked {
          totalRewards += amount;
          dividendsPerNFT += ( amount * precision ) / _currentTokenID;
      }
      emit RewardsDeposited(amount);
  }

  function claimRewards() external {
      require(
          _balances[msg.sender] > 0,
          'Zero Balance'
      );
      _claimRewards(msg.sender);
  }

  function mint(address token, address to, uint256 num, bytes32[] calldata proof) external payable {
      require(
          mintingEnabled,
          'Minting Is Disabled'
      );
      require(
          to != address(0),
          'Zero Address'
      );
      require(
          num > 0,
          'Zero Num'
      );
      if (allowlistEnabled) {
          require(
              MerkleProof.verify(
                  proof,
                  merkleRoot,
                  keccak256(abi.encodePacked(_msgSender()))
              ),
              "User Is Not Whitelisted"
          );
      }

      require(
          mintCost[token] > 0,
          'Invalid Mint Token'
      );
      uint totalCost = mintCost[token] * num;

      if (token == address(0)) {
          require(
              msg.value >= totalCost,
              'Insufficient Value'
          );

          // add logic to swap to USDC if ETH
          (bool s,) = payable(mintRecipient).call{value: msg.value}("");
          require(s, 'Mint Recipient Transfer Failure');

      } else {
          require(
              IERC20(token).balanceOf(msg.sender) >= totalCost,
              'Insufficient Balance'
          );
          require(
              IERC20(token).allowance(msg.sender, address(this)) >= totalCost,
              'Insufficient Allowance'
          );
          require(
              IERC20(token).transferFrom(msg.sender, mintRecipient, totalCost),
              'Error Transfer From'
          );
      }
      
      for (uint i = 0; i < num;) {
          _safeMint(to, _currentTokenID);
          unchecked { ++i; }
      }
  }

  /**
      Cumulative Dividends For A Number Of Tokens
   */
  function getCumulativeDividends(uint256 share) internal view returns (uint256) {
      return ( share * dividendsPerNFT ) / precision;
  }

  /**
      Pending Rewards For `account`
   */
  function pendingRewards(address account) public view returns (uint256) {
      if(_balances[account] == 0){ return 0; }
      if (totalRewards == 0) { return 0; }

      uint256 accountTotalDividends = getCumulativeDividends(_balances[account]);
      uint256 accountTotalExcluded = totalExcluded[account];

      if(accountTotalDividends <= accountTotalExcluded){ return 0; }

      return accountTotalDividends - accountTotalExcluded;
  }

  /**
      Total Supply of NFT
   */
  function totalSupply() external view returns (uint256) {
      return _currentTokenID;
  }

  /**
      Name Of The Collection
   */
  function name() external view override returns (string memory) {
      return _name;
  }

  /**
      Symbol (ticker) Of The Collection
   */
  function symbol() external view override returns (string memory) {
      return _symbol;
  }

  /**
      Returns The Number Of Fractions This NFT Is Split Into
   */
  function numFractions() external view override returns (uint256) {
      return nFractions;
  }

  /**
      Returns The URI To An Image Representing This Fractional Asset
   */
  function tokenURI(uint256) external view override returns (string memory) {
      return baseURI;
  }

  /**
      Returns The URI To An Image Representing This Fractional Asset
   */
  function URI() external view override returns (string memory) {
      return baseURI;
  }

  /**
   * @dev Returns the number of tokens in ``owner``'s account.
   */
  function balanceOf(address owner) external view override returns (uint256 balance) {
      return _balances[owner];
  }

  /**
   * @dev Returns the owner of the `tokenId` token.
   *
   * Requirements:
   *
   * - `tokenId` must exist.
   */
  function ownerOf(uint256 tokenId) public view returns (address owner) {
      require(
          _exists(tokenId),
          'Token Does Not Exist'
      );
      return _owners[tokenId];
  }

  /**
   * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
   * are aware of the ERC721 protocol to prevent tokens from being forever locked.
   *
   * Requirements:
   *
   * - `from` cannot be the zero address.
   * - `to` cannot be the zero address.
   * - `tokenId` token must exist and be owned by `from`.
   * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
   * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
   *
   * Emits a {Transfer} event.
   */
  function safeTransferFrom(
      address from,
      address to,
      uint256 tokenId
  ) external override {
      require(
          _isApprovedOrOwner(_msgSender(), tokenId), 
          "Transfer caller is not owner nor approved"
      );
      _safeTransfer(from, to, tokenId, new bytes(0));
  }

  /**
   * @dev Safely transfers `tokenId` token from `from` to `to`.
   *
   * Requirements:
   *
   * - `from` cannot be the zero address.
   * - `to` cannot be the zero address.
   * - `tokenId` token must exist and be owned by `from`.
   * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
   * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
   *
   * Emits a {Transfer} event.
   */
  function safeTransferFrom(
      address from,
      address to,
      uint256 tokenId,
      bytes calldata data
  ) public override {
      require(
          _isApprovedOrOwner(_msgSender(), tokenId), 
          "Transfer caller is not owner nor approved"
      );
      _safeTransfer(from, to, tokenId, data);
  }