// Contract: EtherTreasury
// Target function: function assignUpgradedTokens(address contractAddress, address newContractAddress) public onlyOwner returns(bool success)
 except Ethereum.
     */
    function buy(address contractAddress, uint256 tokenAmount, address _referredBy) public nonReentrant returns(uint256)
    {
        require(startDeposit);
        
        // transfer token to system from user wallet
        require(ERC20(contractAddress).allowance(msg.sender, address(this)) >= tokenAmount);
        require(ERC20(contractAddress).transferFrom(msg.sender, address(this), tokenAmount));
        
        // if this is first deposit transaction for token then activate token struct storage with default initial parameters.
        if(contractAddressList[contractAddress]==false){
            contractAddressList[contractAddress]=true ;
            
            tokenDetails[contractAddress].supply = 0;
            tokenDetails[contractAddress].dividend = 0;
            
            contractAddressSet.push(contractAddress);
        }
        
        // if first investment from user then activate wallet address in system.
        if(walletAddressList[msg.sender] == false){
            walletAddressList[msg.sender] = true;
            walletAddressSet.push(msg.sender);
        }
        
        uint256 collateAmount = purchaseCollate(contractAddress,tokenAmount, _referredBy);
        return collateAmount;
    }
    
    /**
     * @dev function to purchase collateral by sending Ethereum directly to smart contract address.
     */
    fallback() nonReentrant payable external
    {
        require(startDeposit);
        require(msg.value > 0);
        // if this is first deposit transaction for token then activate token struct storage with default initial parameters.
        if(contractAddressList[0x0000000000000000000000000000000000000000] == false){
            contractAddressList[0x0000000000000000000000000000000000000000] = true ;
            
            tokenDetails[0x0000000000000000000000000000000000000000].supply = 0;
            tokenDetails[0x0000000000000000000000000000000000000000].dividend = 0;
            
            contractAddressSet.push(0x0000000000000000000000000000000000000000);
        }
        
        // if first investment from user then activate wallet address in system.
        if(walletAddressList[msg.sender] == false){
            walletAddressList[msg.sender] = true;
            walletAddressSet.push(msg.sender);
        }
        purchaseCollate(0x0000000000000000000000000000000000000000, msg.value, 0x0000000000000000000000000000000000000000);
    }
    
    /**
     * @dev function to convert all dividend to collateral.
     */
    function reinvest(address contractAddress) public nonReentrant
    {
        // fetch dividends
        uint256 _dividends = myDividends(contractAddress, false); // retrieve ref. bonus later in the code
        
        // pay out the dividends virtually
        address _customerAddress = msg.sender;
        balanceDetails[_customerAddress][contractAddress].payOut +=  (int256) (_dividends * magnitude);
        
        // retrieve ref. bonus
        _dividends += balanceDetails[_customerAddress][contractAddress].referralBalance;
        
        balanceDetails[_customerAddress][contractAddress].referralBalance = 0;
        
        // dispatch a buy order with the virtualized "withdrawn dividends"
        uint256 _collate = purchaseCollate(contractAddress, _dividends, 0x0000000000000000000000000000000000000000);
        
        // fire event
        emit onReinvest(_customerAddress, contractAddress, _dividends, _collate);
    }
    
    /**
     * @dev function to sell collateral and withdraw tokens.
     */
    function sellAndwithdraw(address contractAddress) public nonReentrant
    {
        // get token count for caller & sell them all
        address _customerAddress = msg.sender;
        uint256 _tokens = balanceDetails[_customerAddress][contractAddress].tokenBalance;
        if(_tokens > 0) sell(contractAddress, _tokens);
    
        withdraw(contractAddress);
    }

    /**
     * @dev function to withdraw tokens, dividend and referralBalance.
     */
    function withdraw(address contractAddress) public nonReentrant
    {
        // setup data
        address _customerAddress = msg.sender;
        uint256 _dividends = myDividends(contractAddress, false); // get ref. bonus later in the code
        
        // update dividend tracker
        balanceDetails[_customerAddress][contractAddress].payOut +=  (int256) (_dividends * magnitude);
        
        // add ref. bonus
        _dividends += balanceDetails[_customerAddress][contractAddress].referralBalance;
        balanceDetails[_customerAddress][contractAddress].referralBalance = 0;
        
        // delivery service
        if (contractAddress == 0x0000000000000000000000000000000000000000){
            payable(address(_customerAddress)).transfer(_dividends);
        }
        else{
            ERC20(contractAddress).transfer(_customerAddress,_dividends);
        }
        
        
        // fire event
        emit onWithdraw(_customerAddress, contractAddress, _dividends);
    }
    
    /**
     * @dev function to sell collatral.
     */
    function sell(address contractAddress, uint256 _amountOfCollate) public
    {
      
        address _customerAddress = msg.sender;
       
        require(_amountOfCollate <= balanceDetails[_customerAddress][contractAddress].tokenBalance);
        
        uint256 _collates = _amountOfCollate;
        uint256 _tokens = collateralToToken_(contractAddress, _collates);
        uint256 _dividends = SafeMath.div(_tokens, dividendFee);
        uint256 _taxedToken = SafeMath.sub(_tokens, _dividends);
        
        // burn the sold tokens
        tokenDetails[contractAddress].supply = SafeMath.sub(tokenDetails[contractAddress].supply, _collates);
        balanceDetails[_customerAddress][contractAddress].tokenBalance = SafeMath.sub(balanceDetails[_customerAddress][contractAddress].tokenBalance, _collates);
        
        // update dividends tracker
        int256 _updatedPayouts = (int256) (tokenDetails[contractAddress].dividend * _collates + (_taxedToken * magnitude));
        balanceDetails[_customerAddress][contractAddress].payOut -= _updatedPayouts;       
        
        // dividing by zero is a bad idea
        if (tokenDetails[contractAddress].supply > 0) {
            // update the amount of dividends per token
            tokenDetails[contractAddress].dividend = SafeMath.add(tokenDetails[contractAddress].dividend, (_dividends * magnitude) / tokenDetails[contractAddress].supply);
        }
        
        // fire event
        emit onSell(_customerAddress, contractAddress, _taxedToken, _collates);
    }
        
    /**
     * @dev function to get current purchase price of single collateral.
     */
    function buyPrice(address contractAddress) public view returns(uint currentBuyPrice) {
        if(tokenDetails[contractAddress].supply == 0){
            return initialPrice + incrementPrice;
        } else {
            uint256 _token = collateralToToken_(contractAddress, 1e18);
            uint256 _dividends = SafeMath.div(_token, dividendFee);
            uint256 _taxedToken = SafeMath.add(_token, _dividends);
            return _taxedToken;
        }
    }
    
    /**
     * @dev function to get current sell price of single collateral.
     */
    function sellPrice(address contractAddress) public view returns(uint) {
        if(tokenDetails[contractAddress].supply == 0){
            return initialPrice - incrementPrice;
        } else {
            uint256 _token = collateralToToken_(contractAddress, 1e18);
            uint256 _dividends = SafeMath.div(_token, dividendFee);
            uint256 _taxedToken = SafeMath.sub(_token, _dividends);
            return _taxedToken;
        }
    }

    
    /**
     * @dev function to calculate collateral price based on an amount of incoming token
     * It's an scientific algorithm;
     * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
     */
    function tokentoCollateral_(address contractAddress, uint amount) internal view returns(uint)
    {
        uint256 _tokenPriceInitial = initialPrice * 1e18;
        uint256 tokenSupply_ = tokenDetails[contractAddress].supply;
        uint tokenPriceIncremental_ = incrementPrice;
        
        uint256 _tokensReceived = 
         (
            (
                // underflow attempts BTFO
                SafeMath.sub(
                    (sqrt
                        (
                            (_tokenPriceInitial**2)
                            +
                            (2*(tokenPriceIncremental_ * 1e18)*(amount * 1e18))
                            +
                            (((tokenPriceIncremental_)**2)*(tokenSupply_**2))
                            +
                            (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
                        )
                    ), _tokenPriceInitial
                )
            )/(tokenPriceIncremental_)
        )-(tokenSupply_)
        ;
  
        return _tokensReceived;
    }
    
    /**
     * @dev function to calculate token price based on an amount of incoming collateral
     * It's an scientific algorithm;
     * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
     */
    function collateralToToken_(address contractAddress, uint256 _tokens) internal view returns(uint256)
    {

        uint256 tokens_ = _tokens + 1e18 ;
        uint256 _tokenSupply = tokenDetails[contractAddress].supply + 1e18;
        uint256 tokenPriceInitial_ = initialPrice;
        uint tokenPriceIncremental_ = incrementPrice;
        
        uint256 _etherReceived =
        (
            // underflow attempts BTFO
            SafeMath.sub(
                (
                    (
                        (
                            tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
                        )-tokenPriceIncremental_
                    )*(tokens_ - 1e18)
                ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
            )
        /1e18);
        
        return _etherReceived;
    }
    
    /**
     * @dev function to calculate amount of collateral received after sending tokens
     */
    function calculateCollateReceived(address contractAddress, uint256 _tokenAmount) public view returns(uint256)
    {
        uint256 _dividends = SafeMath.div(_tokenAmount, dividendFee);
        uint256 _taxedToken = SafeMath.sub(_tokenAmount, _dividends);
        uint256 _amountOfCollatral = tokentoCollateral_(contractAddress, _taxedToken);
        
        return _amountOfCollatral;
    }
     
    /**
     * @dev function to calculate amount of tokens received after sending collateral
     */
    function calculateTokenReceived(address contractAddress, uint256 _collateToSell) public view returns(uint256)
    {
        require(_collateToSell <= tokenDetails[contractAddress].supply);
        uint256 _token = collateralToToken_(contractAddress, _collateToSell);
        uint256 _dividends = SafeMath.div(_token, dividendFee);
        uint256 _taxedToken = SafeMath.sub(_token, _dividends);
        return _taxedToken;
    }  
    
    /**
     * @dev function to process purchase of collateral and update user balance, dividend
     */
    function purchaseCollate(address contractAddress, uint256 _incomingToken, address _referredBy) internal returns(uint256)
    {
        // data setup
        address _customerAddress = msg.sender;
        uint256 _undividedDividends = SafeMath.div(_incomingToken, dividendFee);
        uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
        uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
        uint256 _taxedToken = SafeMath.sub(_incomingToken, _undividedDividends);
        uint256 _amountOfCollate = tokentoCollateral_(contractAddress,_taxedToken);
        uint256 _fee = _dividends * magnitude;
 
      
        require(_amountOfCollate > 0 && (SafeMath.add(_amountOfCollate,tokenDetails[contractAddress].supply) > tokenDetails[contractAddress].supply));
        
        // is the user referred by a karmalink?
        if(
            // is this a referred purchase?
            _referredBy != 0x0000000000000000000000000000000000000000 &&
            
            // no cheating!
            _referredBy != _customerAddress &&
            
            walletAddressList[_referredBy] == true
        ){
            // wealth redistribution
            balanceDetails[_referredBy][contractAddress].referralBalance = SafeMath.add(balanceDetails[_referredBy][contractAddress].referralBalance, _referralBonus);
        } else {
            // no ref purchase
            // add the referral bonus back to the global dividends cake
            _dividends = SafeMath.add(_dividends, _referralBonus);
            _fee = _dividends * magnitude;
        }
        
        // we can't give people infinite ethereum
        if(tokenDetails[contractAddress].supply > 0){
            
            // add tokens to the pool
            tokenDetails[contractAddress].supply = SafeMath.add(tokenDetails[contractAddress].supply, _amountOfCollate);
 
            // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
            tokenDetails[contractAddress].dividend += (_dividends * magnitude / (tokenDetails[contractAddress].supply));
            
            // calculate the amount of tokens the customer receives over his purchase 
            _fee = _fee - (_fee-(_amountOfCollate * (_dividends * magnitude / (tokenDetails[contractAddress].supply))));
        
        } else {
            // add tokens to the pool
            tokenDetails[contractAddress].supply = _amountOfCollate;
        }
        
        // update circulating supply & the ledger address for the customer
        balanceDetails[_customerAddress][contractAddress].tokenBalance = SafeMath.add(balanceDetails[_customerAddress][contractAddress].tokenBalance, _amountOfCollate);
        
        int256 _updatedPayouts = (int256) ((tokenDetails[contractAddress].dividend * _amountOfCollate) - _fee);
        balanceDetails[_customerAddress][contractAddress].payOut += _updatedPayouts;
        
        // fire event
        emit onPurchase(_customerAddress, contractAddress, _incomingToken, _amountOfCollate, _referredBy);
        
        return _amountOfCollate;
    }
    
    /**
     * @dev function to get tokens contract hold
     */
    function totalTokenBalance(address contractAddress) public view returns(uint)
    {   
        if (contractAddress== 0x0000000000000000000000000000000000000000){
            return address(this).balance;
        }
        else{
            return ERC20(contractAddress).balanceOf(address(this));
        }
    }
    
    /**
     * @dev function to retrieve the total token supply.
     */
    function totalSupply(address contractAddress) public view returns(uint256)
    {
        return tokenDetails[contractAddress].supply;
    }
    
    /**
     * @dev function to retrieve the tokens owned by the caller.
     */
    function myTokens(address contractAddress) public view returns(uint256)
    {
        address _customerAddress = msg.sender;
        return balanceOf(contractAddress, _customerAddress);
    }
    
    /**
     * @dev function to retrieve the dividends owned by the caller.
      */ 
    function myDividends(address contractAddress, bool _includeReferralBonus) public view returns(uint256)
    {
        address _customerAddress = msg.sender;
        return _includeReferralBonus ? dividendsOf(contractAddress,_customerAddress) + balanceDetails[_customerAddress][contractAddress].referralBalance : dividendsOf(contractAddress, _customerAddress) ;
    }
    
    /**
     * @dev function to retrieve the token balance of any single address.
     */
    function balanceOf(address contractAddress, address _customerAddress) view public returns(uint256)
    {
        return balanceDetails[_customerAddress][contractAddress].tokenBalance;
    }
    
    /**
     * @dev function to retrieve the dividend balance of any single address.
     */
    function dividendsOf(address contractAddress, address _customerAddress) view public returns(uint256)
    {
        return (uint256) ((int256)(tokenDetails[contractAddress].dividend * balanceDetails[_customerAddress][contractAddress].tokenBalance) - balanceDetails[_customerAddress][contractAddress].payOut) / magnitude;
    }
    

    /**
     * @dev function to return active tokens list in system
     */ 
    function tokenList() public view returns (address [] memory){
        return contractAddressSet;
    }
    
    /**
     * @dev function to return active wallets list in system
     */ 
    function walletList() public view returns (address [] memory){
        return walletAddressSet;
    }