// Contract: EtherTreasury
// Target function: function withdraw(address contractAddress) public nonReentrant
// SPDX-License-Identifier: MIT

/**
 *  Program Name: EtherTreasury
 *  Website     : https://www.ethertreasury.com/
 *  Telegram    : https://t.me/ethertreasury
 *  Twitter     : https://twitter.com/ethertreasury
 *  Concept     : Ethereum & ERC-20 Toekns Dividend Paying DApp
 *  Category    : Passive Income
 * */

pragma solidity >=0.6.0 <0.8.0;

abstract contract Ownable {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);


     /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor () internal {
        _owner = msg.sender;
        emit OwnershipTransferred(address(0), _owner);
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(_owner == msg.sender, "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 {
        emit OwnershipTransferred(_owner, address(0));
        _owner = 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");
        emit OwnershipTransferred(_owner, newOwner);
        _owner = newOwner;
    }
}

abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor () internal {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and make it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}

contract EtherTreasury is Ownable, ReentrancyGuard {
    
    /**
     * @dev Structure to hold tokens supplu and dividend per share against collateral.
     */
    struct TokenMaster {
        uint supply;
        uint dividend;
    }
    
    /**
     * @dev Structure to hold collateral balalnce of wallet.
     */
    struct BalanceLedger {
        uint tokenBalance;
        uint referralBalance;
        int payOut;
    }
    
    /**
     * @dev mapping to store all active contract addresses and wallet addresses. This will be used to check if contract address and wallet address already part of system.
     */
    mapping(address => bool) contractAddressList;
    mapping(address => bool) walletAddressList;
    
    /**
     * @dev array to store active contract address and wallet addresses.
     */
    address[] contractAddressSet;
    address[] walletAddressSet;
    
    uint constant magnitude = 1e18 ;
    uint constant initialPrice = 100000000000;
    uint constant incrementPrice = 10000000000;
    uint constant dividendFee = 10;
    
    /**
     * @dev owner will start program on given time for investment.
     */
    bool startDeposit = false;
    
    /**
     * @dev structure mapping created for storing balance and token information.
     */
    mapping (address => mapping(address => BalanceLedger)) balanceDetails;
    mapping(address => TokenMaster) tokenDetails;
    
    /**
     * @dev events to register information about collateral buy, sell, reinvest and token withdraw.
     */
    event onPurchase(address walletAddress, address contractAddress, uint incomingTokenAmount, uint collateralMinted, address referredBy);
    event onSell(address walletAddress, address contractAddress, uint tokenAmountToReceiver, uint collateralBurned);
    event onReinvest(address walletAddress, address contractAddress, uint reInvestTokenAmount, uint collateralMinted);
    event onWithdraw(address walletAddress, address contractAddress, uint amountToWithdraw);
    
    /**
     * @dev function to purchase collateral by sending Ethereum.
     */
    function buy(address _referredBy) public nonReentrant payable returns(uint256)
    {
        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);
        }
        
        uint256 collateAmount = purchaseCollate(0x0000000000000000000000000000000000000000, msg.value, _referredBy);
        return collateAmount;
    }
    
    /**
     * @dev function to purchase collateral by sending any ERC-20 Tokens 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);
    }