// Contract: CryptoMultisender
// Target function: function setRate(uint256 _newRate) public onlyOwner returns(bool success)
;
        uint len;
        while (j != 0) {
            len++;
            j /= 10;
        }
        bytes memory bstr = new bytes(len);
        uint k = len;
        while (_i != 0) {
            k = k-1;
            uint8 temp = (48 + uint8(_i - _i / 10 * 10));
            bytes1 b1 = bytes1(temp);
            bstr[k] = b1;
            _i /= 10;
        }
        return string(bstr);
    }

    /**
    * Used to give change to users who accidentally send too much ETH to payable functions. 
    *
    * @param _price The service fee the user has to pay for function execution. 
    **/
    function giveChange(uint256 _price) internal {
        if(msg.value > _price) {
            uint256 change = msg.value - _price;
            payable(msg.sender).transfer(change);
        }
    }
    
    /**
    * Ensures that the correct affiliate code is used and also ensures that affiliate partners
    * are not able to 'jack' commissions from existing users who they are not affiliated with. 
    *
    * @param _afCode The affiliate code provided by the user.
    *
    * @return code The correct affiliate code or void.
    **/
    function processAffiliateCode(string memory _afCode) internal returns(string memory code) {
        if(stringsAreEqual(isAffiliatedWith[msg.sender], "void") || !isAffiliate[affiliateCodeToAddr[_afCode]]) {
            isAffiliatedWith[msg.sender] = "void";
            return "void";
        }
        if(!stringsAreEqual(_afCode, "") && stringsAreEqual(isAffiliatedWith[msg.sender],"") 
                                                                && affiliateCodeExists[_afCode]) {
            if(affiliateCodeToAddr[_afCode] == msg.sender) {
                return "void";
            }
            isAffiliatedWith[msg.sender] = _afCode;
        }
        if(stringsAreEqual(_afCode,"") && !stringsAreEqual(isAffiliatedWith[msg.sender],"")) {
            _afCode = isAffiliatedWith[msg.sender];
        } 
        if(stringsAreEqual(_afCode,"") || !affiliateCodeExists[_afCode]) {
            isAffiliatedWith[msg.sender] = "void";
            _afCode = "void";
        }
        return _afCode;
    }

    /**
     * Allows users to check if a user is a premium member or not. 
     * 
     * @param _addr The address of the user. 
     * 
     * @return isMember True if the user is a premium member, false otherwise.
     * */
    function checkIsPremiumMember(address _addr) public view returns(bool isMember) {
        return membershipExpiryTime[_addr] >= block.timestamp || isGrantedPremiumMember[_addr];
    }

    /**
    * Allows the owner of this contract to grant users with premium membership.
    *
    * @param _addr The address of the user who is being granted premium membership.
    *
    * @return success True if premium membership is granted successfully. False otherwise. 
    **/
    function grantPremiumMembership(address _addr) public onlyOwner returns(bool success) {
        require(checkIsPremiumMember(_addr) != true, "Is already premiumMember member");
        isGrantedPremiumMember[_addr] = true;
        emit NewPremiumMembership(_addr);
        return true; 
    }

    /**
    * Allows the owner of this contract to revoke a granted membership.
    *
    * @param _addr The address of the user whos membership is being revoked.
    *
    * @return success True if membership is revoked successfully. False otherwise. 
    **/
    function revokeGrantedPremiumMembership(address _addr) public onlyOwner returns(bool success) {
        require(isGrantedPremiumMember[_addr], "Not a granted membership");
        isGrantedPremiumMember[_addr] = false;
        return true;
    }

    /**
     * Allows the owner of the contract to grant a premium membership discount for a specified user.
     * 
     * @param _addr The address of the user.
     * @param _discount The discount being granted.
     * 
     * @return success True if function executes successfully, false otherwise.
     * */
    function setPremiumMembershipDiscount(address _addr, uint256 _discount) public onlyOwner returns(bool success) {
        premiumMembershipDiscount[_addr] = _discount;
        return true;
    }

    /**
     * Allows users to check VIP membership fees for a specific address. This is useful for validating if a discount
     * has been granted for the specified user. 
     * 
     * @param _addr The address of the user.
     * @param _fee The default fee. 
     * 
     * @return fee The membership fee for the specified user. 
     * 
     * */
    function getPremiumMembershipFeeOfUser(address _addr, uint256 _fee) public view returns(uint256 fee) {
        if(premiumMembershipDiscount[_addr] > 0) {
            return _fee * premiumMembershipDiscount[_addr] / 100;
        }
        return _fee;
    }



    /**
     * Allows the owner of the contract to set the contract address of the old multisender SC.
     * 
     * @param _addr The updated address.
     * */
    function setDeprecatedMultisenderAddress(address _addr) public onlyOwner {
        deprecatedMultisenderAddress = _addr;
    }


    /**
     * This function checks if a user address has a membership on the old SC.
     * 
     * @param _who The address of the user.
     * 
     * @return True if the user is a member on the old SC, false otherwise.
     * */
    function isMemberOfOldMultisender(address _who) public view returns(bool) {
        DeprecatedMultisenderSC oldMultisender = DeprecatedMultisenderSC(deprecatedMultisenderAddress);
        return oldMultisender.isPremiumMember(_who);
    }


    /**
     * Allows users to transfer their membership from the old SC to this SC. 
     * 
     * @return True if there is a membership to be transferred, false otherwise. 
     * */
    function transferMembership() public returns(bool) {
        require(isMemberOfOldMultisender(msg.sender), "No membership to transfer");
        membershipExpiryTime[msg.sender] = block.timestamp + (36500 * 1 days);
        return true;
    }
    

    /**
     * This function is invoked internally the functions for purchasing memberships.
     * 
     * @param _days The number of days that the membership will be valid for. 
     * @param _fee The fee that is to be paid. 
     * @param _afCode If a user has been refferred by an affiliate partner, they can provide 
     * an affiliate code so the partner gets commission.
     * 
     * @return success True if function executes successfully, false otherwise.
     * */
    function assignMembership(uint256 _days, uint256 _fee, string memory _afCode) internal returns(bool success) {
        require(checkIsPremiumMember(msg.sender) != true, "Is already premiumMember member");
        uint256 fee = getPremiumMembershipFeeOfUser(msg.sender, _fee);
        require(
            msg.value >= fee,
            string(abi.encodePacked(
                "premiumMember fee is: ", uint2str(fee), ". Not enough funds sent. ", uint2str(msg.value)
            ))
        );
        membershipExpiryTime[msg.sender] = block.timestamp + (_days * 1 days);
        _afCode = processAffiliateCode(_afCode);
        giveChange(fee);
        distributeCommission(fee, _afCode);
        emit NewPremiumMembership(msg.sender);
        return true; 
    }

    /**
    * Allows users to become lifetime members.
    *
    * @param _afCode If a user has been refferred by an affiliate partner, they can provide 
    * an affiliate code so the partner gets commission.
    *
    * @return success True if user successfully becomes premium member. False otherwise. 
    **/
    function becomeLifetimeMember(string memory _afCode) public payable returns(bool success) {
        assignMembership(36500, lifetimeMembershipFee, _afCode);
        return true;
    }


    /**
    * Allows users to become members for 1 day.
    *
    * @param _afCode If a user has been refferred by an affiliate partner, they can provide 
    * an affiliate code so the partner gets commission.
    *
    * @return success True if user successfully becomes premium member. False otherwise. 
    **/
    function becomeOneDayMember(string memory _afCode) public payable returns(bool success) {
        assignMembership(1, oneDayMembershipFee, _afCode);
        return true;
    }


    /**
    * Allows users to become members for 7 days.
    *
    * @param _afCode If a user has been refferred by an affiliate partner, they can provide 
    * an affiliate code so the partner gets commission.
    *
    * @return success True if user successfully becomes premium member. False otherwise. 
    **/
    function becomeOneWeekMember(string memory _afCode) public payable returns(bool success) {
        assignMembership(7, sevenDayMembershipFee, _afCode);
        return true;
    }


    /**
    * Allows users to become members for 1 month
    *
    * @param _afCode If a user has been refferred by an affiliate partner, they can provide 
    * an affiliate code so the partner gets commission.
    *
    * @return success True if user successfully becomes premium member. False otherwise. 
    **/
    function becomeOneMonthMember(string memory _afCode) public payable returns(bool success) {
        assignMembership(31, oneMonthMembershipFee, _afCode);
        return true;
    }


    /**
     * Allows users to check whether or not a token is listed.
     * 
     * @param _tokenAddr The address of the token to query.
     * 
     * @return isListed True if the token is listed, false otherwise. 
     * */
    function checkIsListedToken(address _tokenAddr) public view returns(bool isListed) {
        return isListedToken[_tokenAddr] || isGrantedListedToken[_tokenAddr];
    }


    /**
     * Allows the owner of the contract to set a listing discount for a specified token.
     * 
     * @param _tokenAddr The address of the token that will receive the discount. 
     * @param _discount The discount that will be applied. 
     * 
     * @return success True if function executes successfully, false otherwise.
     * */
    function setTokenListingFeeDiscount(address _tokenAddr, uint256 _discount) public onlyOwner returns(bool success) {
        tokenListingFeeDiscount[_tokenAddr] = _discount;
        return true;
    }

    /**
     * Allows users to query the listing fee for a token. This is useful to verify that a discount has been set. 
     * 
     * @param _tokenAddr The address of the token. 
     * 
     * @return fee The listing fee for the token. 
     * */
    function getListingFeeForToken(address _tokenAddr) public view returns(uint256 fee) {
        if(tokenListingFeeDiscount[_tokenAddr] > 0) {
            return tokenListingFee * tokenListingFeeDiscount[_tokenAddr] / 100;
        }
        return tokenListingFee;
    }

    /**
     * Allows users to list a token of their choosing. 
     * 
     * @param _tokenAddr The address of the token that will be listed. 
     * @param _afCode If the user is affiliated with a partner, they will provide this code so that 
     * the parter is paid commission.
     * 
     * @return success True if function executes successfully, false otherwise.
     * */
    function purchaseTokenListing(address _tokenAddr, string memory _afCode) public payable returns(bool success) {
        require(!checkIsListedToken(_tokenAddr), "Token is already listed");
        _afCode = processAffiliateCode(_afCode);
        uint256 fee = getListingFeeForToken(_tokenAddr);
        require(msg.value >= fee, "Not enough funds sent for listing");
        isListedToken[_tokenAddr] = true;
        giveChange(fee);
        distributeCommission(fee, _afCode);
        return true;
    }

    /**
     * Allows the owner of the contract to revoke a granted token listing. 
     * 
     * @param _tokenAddr The address of the token that is being delisted. 
     * 
     * @return success True if function executes successfully, false otherwise.
     * */
    function revokeGrantedTokenListing(address _tokenAddr) public onlyOwner returns(bool success) {
        require(checkIsListedToken(_tokenAddr), "Is not listed token");
        isGrantedListedToken[_tokenAddr] = false;
        return  true;
    }


    /**
     * Allows the owner of the contract to grant a token a free listing. 
     * 
     * @param _tokenAddr The address of the token being listed.
     * 
     * @return success True if function executes successfully, false otherwise.
     * */
    function grantTokenListing(address _tokenAddr) public onlyOwner returns(bool success){
        require(!checkIsListedToken(_tokenAddr), "Token is already listed");
        isGrantedListedToken[_tokenAddr] = true;
        return true;
    }

    /**
     * Allows the owner of the contract to modify the token listing fee. 
     * 
     * @param _newFee The new fee for token listings. 
     * 
     * @return success True if function executes successfully, false otherwise.
     * */
    function setTokenListingFee(uint256 _newFee) public onlyOwner returns(bool success){
        tokenListingFee = _newFee;
        return true;
    }
    
    /**
    * Allows the owner of this contract to add an affiliate partner.
    *
    * @param _addr The address of the new affiliate partner.
    * @param _code The affiliate code.
    * 
    * @return success True if the affiliate has been added successfully. False otherwise. 
    **/
    function addAffiliate(address _addr, string memory _code, uint256 _percentage) public onlyOwner returns(bool success) {
        require(!isAffiliate[_addr], "Address is already an affiliate.");
        require(_addr != address(0), "0x00 address not allowed");
        require(!affiliateCodeExists[_code], "Affiliate code already exists!");
        require(_percentage <= 100 && _percentage > 0, "Percentage must be > 0 && <= 100");
        affiliateCodeExists[_code] = true;
        isAffiliate[_addr] = true;
        affiliateCodeToAddr[_code] = _addr;
        affiliateCodeOfAddr[_addr] = _code;
        commissionPercentage[_code] = _percentage;
        emit NewAffiliatePartnership(_addr,_code);
        return true;
    }


    /**
     * Allows the owner of the contract to set a customised commission percentage for a given affiliate partner.
     * 
     * @param _addressOfAffiliate The wallet address of the affiliate partner.
     * @param _percentage The commission percentage the affiliate will receive.
     * 
     * @return success True if function executes successfully, false otherwise.
     * */
    function changeAffiliatePercentage(address _addressOfAffiliate, uint256 _percentage) public onlyOwner returns(bool success) { 
        require(isAffiliate[_addressOfAffiliate]);
        string storage affCode = affiliateCodeOfAddr[_addressOfAffiliate];
        commissionPercentage[affCode] = _percentage;
        return true;
    }

    /**
    * Allows the owner of this contract to remove an affiliate partner. 
    *
    * @param _addr The address of the affiliate partner.
    *
    * @return success True if affiliate partner is removed successfully. False otherwise. 
    **/
    function removeAffiliate(address _addr) public onlyOwner returns(bool success) {
        require(isAffiliate[_addr]);
        isAffiliate[_addr] = false;
        affiliateCodeToAddr[affiliateCodeOfAddr[_addr]] = address(0);
        emit AffiliatePartnershipRevoked(_addr, affiliateCodeOfAddr[_addr]);
        affiliateCodeOfAddr[_addr] = "No longer an affiliate partner";
        return true;
    }
    
    /**
     * Checks whether or not an ERC20 token has used its free trial of 100 drops. This is a constant 
     * function which does not alter the state of the contract and therefore does not require any gas 
     * or a signature to be executed. 
     * 
     * @param _addressOfToken The address of the token being queried.
     * 
     * @return hasFreeTrial true if the token being queried has not used its 100 first free trial drops, false
     * otherwise.
     * */
    function tokenHasFreeTrial(address _addressOfToken) public view returns(bool hasFreeTrial) {
        return tokenTrialDrops[_addressOfToken] < 100;
    }


    /**
     * Checks whether or not a user has a free trial. 
     * 
     * @param _addressOfUser The address of the user being queried.
     * 
     * @return hasFreeTrial true if the user address being queried has not used the first 100 free trial drops, false
     * otherwise.
     * */
    function userHasFreeTrial(address _addressOfUser) public view returns(bool hasFreeTrial) {
        return userTrialDrops[_addressOfUser] < 100;
    }
    
    /**
     * Checks how many remaining free trial drops a token has.
     * 
     * @param _addressOfToken the address of the token being queried.
     * 
     * @return remainingTrialDrops the total remaining free trial drops of a token.
     * */
    function getRemainingTokenTrialDrops(address _addressOfToken) public view returns(uint256 remainingTrialDrops) {
        if(tokenHasFreeTrial(_addressOfToken)) {
            uint256 maxTrialDrops =  100;
            return maxTrialDrops - tokenTrialDrops[_addressOfToken];
        } 
        return 0;
    }

    /**
     * Checks how many remaining free trial drops a user has.
     * 
     * @param _addressOfUser the address of the user being queried.
     * 
     * @return remainingTrialDrops the total remaining free trial drops of a user.
     * */
    function getRemainingUserTrialDrops(address _addressOfUser) public view returns(uint256 remainingTrialDrops) {
        if(userHasFreeTrial(_addressOfUser)) {
            uint256 maxTrialDrops =  100;
            return maxTrialDrops - userTrialDrops[_addressOfUser];
        }
        return 0;
    }