/**
 *Submitted for verification at FTMScan.com on 2023-10-30
*/

/**
 * @title DXLock - Empowering Trust through Token Locking
 * @dev Secure, User-Friendly Smart Contract to Lock Liquidity and Regular Tokens.
 *
 * 🚀 Introduction:
 * Welcome to DXLock, the pinnacle of token locking on the blockchain! Developed with passion and precision,
 * DXLock stands out as a beacon of trust and commitment in the crypto world. This smart contract is meticulously
 * crafted to lock both liquidity tokens and regular ERC20 tokens, ensuring a secure and transparent environment
 * for your assets.
 *
 * 🌐 Visit DXLock:
 * Dive deeper into the world of DXLock by visiting our platform at [dx.app](https://dx.app). Discover a treasure trove of features,
 * tutorials, and support to elevate your token locking experience!
 *
 * 💡 Features:
 * 1. **Liquidity Locking**: Cement your project's credibility by locking liquidity tokens. Show the world that you're here to stay!
 * 2. **Token Locking**: Not just for liquidity! Lock any ERC20 tokens with ease and confidence.
 * 3. **Time-locked Security**: Your tokens are safe and sound until the predetermined unlock time hits the clock.
 * 4. **Transparent and Trustworthy**: Open-source and audited, DXLock is a fortress of reliability.
 *
 * 🛡️ Security:
 * Your trust is our top priority. DXLock is fortified with industry-leading security practices to shield your assets
 * and ensure a seamless experience. Though thorough audits have been conducted, we encourage users to do their own
 * research and verify the contract's integrity before engaging.
 *
 * 📖 How to Use:
 * Engaging with DXLock is a breeze! Simply deposit your tokens, set the lock duration, and rest easy knowing
 * your assets are in good hands. Once the lock period concludes, withdrawing is just a click away.
 *
 * 👥 Community and Support:
 * Join our vibrant community and connect with the DXLock team and fellow users! Your feedback and questions are invaluable
 * to us, as we continually strive to enhance DXLock’s functionality and user experience.
 *
 * 📜 License:
 * DXLock is proudly released under the MIT License. We believe in openness and the power of community-driven innovation.
 *
 * @author The DXLock Team
 * @notice Utilize DXLock at your own discretion. We’ve done everything to ensure its security, but the final responsibility lies with the user.
 */

// SPDX-License-Identifier: MIT

pragma solidity 0.8.14;

interface IERC20 {
    function transfer(address to, uint256 value) external returns (bool);

    function approve(address spender, uint256 value) external returns (bool);

    function transferFrom(address from, address to, uint256 value) external returns (bool);

    function totalSupply() external view returns (uint256);

    function balanceOf(address who) external view returns (uint256);

    function allowance(address owner, address spender) external view returns (uint256);

    event Transfer(address indexed from, address indexed to, uint256 value);

    event Approval(address indexed owner, address indexed spender, uint256 value);
}

abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

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 Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing 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);
    }
}

/**
 * @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);
        }
    }
}

interface decentralizedStorage {
    function addNewPersonalLocker(address _lockedTokens, uint256 _lockedTime, address _lockContract, string memory _logo, uint256 _vestCount, uint256 _lockerType) external;
    function transferPersonalLocker(address _newOwner, uint256 _personalLockerCount) external;
    function unlockPersonalLocker(uint256 _personalLockerCount) external;
    function extendPersonalLocker(uint256 _newLockTimeStamp, uint256 _personalLockerCount) external;
    function changeLogoPersonalLocker(string memory _logo, uint256 _personalLockerCount) external;
    function getPersonalLockerCount(address _owner) external returns (uint256);
    function getBurnContractAddress() external view returns (address);
}

interface FeeCheckContractInterface {

    function getFees(string memory _dappName) external view returns(uint256);
    function getWhitelistFees(string memory _dappWhitelistName) external view returns(uint256);
}

interface FeeDepositContractInterface {

    function payment(uint256 _dappNum) external payable;
}

interface ReferralContract {

    function getDiscountedPrice(string memory _code) external returns(uint256);
    function validateCode(string memory _code) external returns(bool);
    function fetchCodeOwner(string memory _code) external returns(address);
    function fetchCodeOwnerPercentage(string memory _code) external returns(uint256);
    function updateReferrerAmounts(address _referrer, uint256 _updateAmount)  external returns(bool);  
    function updateCodeUseNumber(string memory _code, address _presaleAddress) external returns(bool);
}

contract PersonalTokenLockerWithRewards is Ownable {

    bool public feePaid;
    uint256 public percFeeAmount;

    bool public vesting;
    uint256 public vestCount = 1;
    uint256 public vestCountLeft;
    uint256 public vestedRounds;
    uint256 public vestInterval;
    uint256 public vestAmountPerCycle;

    uint256 public LockedAmount;

    uint256 public personalLockerCount;
    address public storagePersonal;

    uint256 public RewardsNativeClaimed;
    uint256 public ReflectionClaimed;
    bool public reflection = true;
    mapping(address => uint256) public RewardsTokenClaimed;
    uint256 public LockExpireTimestamp;
    uint256 public LockerCreationTimestamp;
    uint256 public LockerLastVestingTimestamp;

    IERC20 public PersonalLockerToken;
    IERC20 public PersonalRewardToken;
    uint256 public LockerType = 2;
    bool public tokenWithdrawn;

    address internal feeDeposit;
    uint256 public relockPercAmount;
    bool public relockAfterExpire = true;

    constructor (address _lockTokenAddress, address _rewardTokenAddress, uint256 _lockTimeEnd, uint256 _personalLockerCount, address _lockerStorage, uint256 _lockingAmount, uint256 _vestCount, bool _feeState, uint256 _percFee, uint256 _relockPercAmount, address _feeDeposit) {
        require(_lockTokenAddress != _rewardTokenAddress, "Cant get the same Token as Reward");
        require(_lockTimeEnd > block.timestamp, "Please lock longer than now");
        require(_lockingAmount > 0,"can't lock 0 Tokens");
        require(_vestCount > 0,"vest cannot be 0");

        if (_vestCount > 1) {
            vesting = true;
            vestCount = _vestCount;
            vestCountLeft = _vestCount;
            vestAmountPerCycle = _lockingAmount / _vestCount;
            vestInterval = (_lockTimeEnd - block.timestamp) / _vestCount;
        }

        LockedAmount = _lockingAmount;
        PersonalLockerToken = IERC20(_lockTokenAddress);
        PersonalRewardToken = IERC20(_rewardTokenAddress);
        LockExpireTimestamp = _lockTimeEnd;
        personalLockerCount = _personalLockerCount;
        storagePersonal = _lockerStorage;

        LockerCreationTimestamp = block.timestamp;
        LockerLastVestingTimestamp = block.timestamp;

        feePaid = _feeState;
        percFeeAmount = _percFee;

        feeDeposit = _feeDeposit;
        relockPercAmount = _relockPercAmount;

        _transferOwnership(tx.origin);
    }

    receive() external payable {

    }

    function changeLogo(string memory _logo) external onlyOwner {
        decentralizedStorage(storagePersonal).changeLogoPersonalLocker(_logo, personalLockerCount);
    }

    function CheckLockedBalance() public view returns (uint256){
        return PersonalLockerToken.balanceOf(address(this));
    }

    //This function will withdraw the amount vested Tokens, in case the LockerTime is over you can also use the function for "unlockTokensAfterTimestamp" otherwise you wont get reward tokens back.
    function WithdrawVestedTokens() external onlyOwner {
        require(feePaid, "Please pay the fee first");
        require(vesting, "Vesting disabled");

        uint256 cycles = (block.timestamp - LockerCreationTimestamp) / vestInterval;
        require(vestedRounds < vestCount,"no vest left");
        require((cycles - vestedRounds) > 0,"vesting not unlocked");
        require(cycles > 0, "No cycles available");

        if ((cycles - vestedRounds) >= vestCountLeft) {
            cycles = vestCountLeft;
            vestedRounds = vestCount;
            PersonalLockerToken.transfer(owner(), PersonalLockerToken.balanceOf(address(this)));
            vestCountLeft = 0;
            LockedAmount = 0;

        } else {
            vestCountLeft -= (cycles - vestedRounds);
            uint256 _vestedAmount = vestAmountPerCycle * (cycles - vestedRounds);
            vestedRounds = cycles;
            PersonalLockerToken.transfer(owner(), _vestedAmount);
            LockedAmount -= _vestedAmount;
        }
        LockerLastVestingTimestamp = block.timestamp;

        if (!tokenWithdrawn){
            decentralizedStorage(storagePersonal).unlockPersonalLocker(personalLockerCount);
            tokenWithdrawn = true;
        }
    }

    function ExtendPersonalLocker(uint256 _newLockTime) external onlyOwner {
        require(LockExpireTimestamp < _newLockTime, "You cant reduce locktime...");
        require(block.timestamp < _newLockTime, "You cant extend locktime in the past");
        require(!tokenWithdrawn, "Tokens were already withdrawn");

        if (block.timestamp > (LockExpireTimestamp + 300)) {
            uint256 amountFee = (LockedAmount * relockPercAmount) / 1000;
            PersonalLockerToken.transfer(feeDeposit, amountFee);
            LockedAmount -= amountFee;
        }

        LockExpireTimestamp = _newLockTime;
        //Change also the vesting interval
        if(vestCount > 1){
            vestInterval = (_newLockTime - LockerCreationTimestamp) / vestCount;
        }
        decentralizedStorage(storagePersonal).extendPersonalLocker(_newLockTime, personalLockerCount);
    }

    function transferOwnership(address _newOwner) public override onlyOwner {
        _transferOwnership(_newOwner);
        decentralizedStorage(storagePersonal).transferPersonalLocker(_newOwner, personalLockerCount);
    }

    function unlockTokensAfterTimestamp() external onlyOwner {
        require(block.timestamp >= LockExpireTimestamp, "Token is still Locked");
        require(feePaid, "The fee is not yet paid");

        PersonalLockerToken.transfer(owner(), PersonalLockerToken.balanceOf(address(this)));
        LockedAmount = 0;
        
        if (!tokenWithdrawn){
            decentralizedStorage(storagePersonal).unlockPersonalLocker(personalLockerCount);
            tokenWithdrawn = true;
        }

    }

    function payFee() external onlyOwner {
        require(!feePaid, "The fee has already been paid");

        uint256 feeToPay = (PersonalLockerToken.balanceOf(address(this)) * percFeeAmount) / 1000;
        PersonalLockerToken.transfer(decentralizedStorage(storagePersonal).getBurnContractAddress(), feeToPay);
        feePaid = true;
    }

    function unlockPercentageAfterTimestamp(uint256 _percentage) external onlyOwner {
        require(_percentage <= 100, "You can't withdraw more than 100%");
        require(block.timestamp >= LockExpireTimestamp, "Token is still Locked");
        require(feePaid, "Fee not paid yet");

        uint256 amountUnlock = (PersonalLockerToken.balanceOf(address(this)) * _percentage) / 100;
        PersonalLockerToken.transfer(owner(), amountUnlock);
        LockedAmount -= amountUnlock;

        if (!tokenWithdrawn){
            decentralizedStorage(storagePersonal).unlockPersonalLocker(personalLockerCount);
            tokenWithdrawn = true;
        }
    }

    function WithdrawRewardNativeToken() external onlyOwner {
        uint256 amountFee = (address(this).balance * percFeeAmount) / 1000;
        payable(decentralizedStorage(storagePersonal).getBurnContractAddress()).transfer(amountFee);
        uint256 amount = address(this).balance;
        payable(owner()).transfer(amount);
        RewardsNativeClaimed += amount;
    }

    function WithdrawTokensReward(address _token) external onlyOwner {
        require(_token != address(PersonalLockerToken), "You can't unlock the Tokens you locked with this function!");

        uint256 amountFee = (IERC20(_token).balanceOf(address(this))* percFeeAmount) / 1000;
        IERC20(_token).transfer(decentralizedStorage(storagePersonal).getBurnContractAddress(), amountFee);

        uint256 amount = IERC20(_token).balanceOf(address(this));
        IERC20(_token).transfer(owner(), amount);
        RewardsTokenClaimed[_token] += amount;
    }

    function WithdrawReflectionReward() external onlyOwner {
        uint256 amountReflection;
        if(vesting){
            amountReflection = (IERC20(PersonalLockerToken).balanceOf(address(this))) - (vestCountLeft*vestAmountPerCycle);
        }
        else {

            amountReflection = (IERC20(PersonalLockerToken).balanceOf(address(this))) - LockedAmount;

        }
        require(amountReflection > 0,"no reflection left for claim");
        uint256 amountFee = (amountReflection * percFeeAmount) / 1000;
        IERC20(PersonalLockerToken).transfer(decentralizedStorage(storagePersonal).getBurnContractAddress(), amountFee);

        uint256 amount = amountReflection - amountFee;
        IERC20(PersonalLockerToken).transfer(owner(), amount);
        ReflectionClaimed += amount;
    }


}