contract AugustusSwapper is ReentrancyGuard, Ownable {
    using SafeERC20 for IERC20;
    using SafeMath for uint256;
    using Address for address;

    //Ether token address used when to or from in swap is Ether
    address constant private ETH_ADDRESS = address(
        0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
    );

    //External call is allowed to whitelisted addresses only.
    //Contract address of all supported exchanges must be put in whitelist
    mapping(address => bool) private _whitelisteds;

    //for 2% enter 200. For 0.2% enter 20. Supports upto 2 decimal places
    uint256 private _fee;

    address payable private _feeWallet;

    IGST2 private _gasToken;

    bool private _paused;

    event WhitelistAdded(address indexed account);
    event WhitelistRemoved(address indexed account);
    event Swapped(
        address indexed user,
        address indexed srcToken,
        address indexed destToken,
        uint256 srcAmount,
        uint256 receivedAmount
    );
    event Paused();
    event Unpaused();

    modifier onlySelf() {
        require(
            msg.sender == address(this),
            "AugustusSwapper: Invalid access!!"
        );
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     */
    modifier whenNotPaused() {
        require(!_paused, "Pausable: paused");
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     */
    modifier whenPaused() {
        require(_paused, "Pausable: not paused");
        _;
    }

    /**
    * @dev Constructor
    * It will whitelist the contarct itself
    */
    constructor(address payable feeWallet, address gasToken) public {
        require(feeWallet != address(0), "Invalid address!!");
        require(gasToken != address(0), "Invalid gas token!!");

        _feeWallet = feeWallet;
        _gasToken = IGST2(gasToken);

        _whitelisteds[address(this)] = true;
        emit WhitelistAdded(address(this));
    }

    /**
    * @dev Fallback method to allow exchanges to transfer back ethers for a particular swap
    * It will only allow contracts to send funds to it
    */
    function() external payable {
        address account = msg.sender;
        require(
            account.isContract(),
            "Sender is not a contract!!"
        );
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() external view returns (bool) {
        return _paused;
    }

    /**
     * @dev Called by a pauser to pause, triggers stopped state.
     */
    function pause() external onlyOwner whenNotPaused {
        _paused = true;
        emit Paused();
    }

    /**
     * @dev Called by a pauser to unpause, returns to normal state.
     */
    function unpause() external onlyOwner whenPaused {
        _paused = false;
        emit Unpaused();
    }

    /**
    * @dev Allows owner to change fee wallet
    * @param feeWallet Address of the new fee wallet
    */
    function changeFeeWallet(address payable feeWallet) external onlyOwner {
        _feeWallet = feeWallet;
    }

    /**
    * @dev Returns the fee wallet address
    */
    function getFeeWallet() external view returns(address) {
        return _feeWallet;
    }

    /**
    * @dev Allows owner to change fee
    * @param fee New fee percentage
    */
    function changeFee(uint256 fee) external onlyOwner {
        _fee = fee;
    }

    /**
    * @dev returns the current fee percentage
    */
    function getFee() external view returns(uint256) {
        return _fee;
    }

    /**
    * @dev Allows owner of the contract to whitelist an address
    * @param account Address of the account to be whitelisted
    */
    function addWhitelisted (address account) external onlyOwner {
        _whitelisteds[account] = true;
        emit WhitelistAdded(account);
    }

    /**
    * @dev Allows owner of the contract to remove address from a whitelist
    * @param account Address of the account the be removed
    */
    function removeWhitelistes(address account) external onlyOwner {
        _whitelisteds[account] = false;
        emit WhitelistRemoved(account);
    }

    /**
    * @dev Allows onwers of the contract to whitelist addresses in bulk
    * @param accounts An array of addresses to be whitelisted
    */
    function addWhitelistedBulk(
        address[] calldata accounts
    )
        external
        onlyOwner
    {
        for (uint256 i = 0; i < accounts.length; i++) {
            _whitelisteds[accounts[i]] = true;
            emit WhitelistAdded(accounts[i]);
        }
    }

    /**
    * @dev Allows this contract to make approve call for a token
    * This method is expected to be called using externalCall method.
    * @param token The address of the token
    * @param to The address of the spender
    * @param amount The amount to be approved
    */
    function approve(
        address token,
        address to,
        uint256 amount
    )
        external
        onlySelf
    {
        require(amount > 0, "Amount should be greater then 0!!");
        //1. Check for valid whitelisted address
        require(
            isWhitelisted(to),
            "AugustusSwapper: Not a whitelisted address!!"
        );

        //2. Check for ETH address
        if (token != ETH_ADDRESS){
            //3. Approve
            IERC20 _token = IERC20(token);
            _token.safeApprove(to, amount);
        }

    }

    /**
    * @dev Allows owner of the contract to transfer tokens any tokens which are assigned to the contract
    * This method is for saftey if by any chance tokens or ETHs are assigned to the contract by mistake
    * @dev token Address of the token to be transferred
    * @dev destination Recepient of the token
    * @dev amount Amount of tokens to be transferred
    */
    function ownerTransferTokens(
        address token,
        address payable destination,
        uint256 amount
    )
        external
        onlyOwner
    {
        transferTokens(token, destination, amount);
    }

    /**
    * @dev Allows owner of the contract to mint more gas tokens
    * @param amount Amount of gas tokens to mint
    */
    function mintGasTokens(uint256 amount) external onlyOwner {
        _gasToken.mint(amount);
    }

    /**
    * @dev The function which performs the actual swap.
    * The call data to the actual exchanges must be built offchain
    * and then sent to this method. It will be call those external exchanges using
    * data passed through externalCall function
    * It is a nonreentrant function
    * @param sourceToken Address of the source token
    * @param destinationToken Address of the destination token
    * @param sourceAmount Amount of source tokens to be swapped
    * @param minDestinationAmount Minimu destination token amount expected out of this swap
    * @param callees Address of the external callee. This will also contain address of exchanges
    * where actual swap will happen
    * @param exchangeData Concatenated data to be sent in external call to the above callees
    * @param startIndexes start index of calldata in above data structure for each callee
    * @param values Amount of ethers to be sent in external call to each callee
    * @param mintPrice Price of gas at the time of minting of gas tokens, if any. In wei
    */
    function performSwap(
        address sourceToken,
        address destinationToken,
        uint256 sourceAmount,
        uint256 minDestinationAmount,
        address[] memory callees,
        bytes memory exchangeData,
        uint256[] memory startIndexes,
        uint256[] memory values,
        uint256 mintPrice
    )
        public
        payable
        whenNotPaused
        nonReentrant
    {
        //Basic sanity check
        require(callees.length > 0, "No callee provided!!");
        require(
            callees.length + 1 == startIndexes.length,
            "Start indexes must be 1 greater then number of callees!!"
        );
        require(sourceToken != address(0), "Invalid source token!!");
        require(destinationToken != address(0), "Inavlid destination address");

        uint initialGas = gasleft();

        //If source token is not ETH than transfer required amount of tokens
        //from sender to this contract
        if (sourceToken != ETH_ADDRESS){
            IERC20(sourceToken).safeTransferFrom(msg.sender, address(this), sourceAmount);
        }

        for (uint256 i = 0; i < callees.length; i++) {

            require(isWhitelisted(callees[i]), "Callee is not whitelisted!!");

            bool result = externalCall(
                callees[i],//destination
                values[i],//value to send
                startIndexes[i],// start index of call data
                startIndexes[i+1].sub(startIndexes[i]),// length of calldata
                exchangeData// total calldata
            );
            require(result, "External call failed!!");
        }
        uint256 receivedAmount = tokenBalance(destinationToken, address(this));

        require(
            receivedAmount >= minDestinationAmount,
            "Received amount of tokens are less then expected!!"
        );

        uint256 fee = calculateFee(
            sourceToken,
            receivedAmount,
            callees.length
        );

        if (fee > 0) {
            receivedAmount = receivedAmount.sub(fee);
            transferTokens(destinationToken, _feeWallet, fee);
        }

        transferTokens(destinationToken, msg.sender, receivedAmount);

        emit Swapped(
            msg.sender,
            sourceToken,
            destinationToken,
            sourceAmount,
            receivedAmount
        );

        if (mintPrice > 0){
            refundGas(initialGas, mintPrice);
        }
    }

    /**
    * @dev Returns whether given addresses is whitelisted or not
    * @param account The account to be checked
    * @return bool
    */
    function isWhitelisted(address account) public view returns(bool) {
        return _whitelisteds[account];
    }

    /**
    * @dev Helper method to refund gas using gas tokens
    */
    function refundGas(uint256 initialGas, uint256 mintPrice) private {

        uint256 mintBase = 32254;
        uint256 mintToken = 36543;
        uint256 freeBase = 14154;
        uint256 freeToken = 6870;
        uint256 reimburse = 24000;

        uint256 tokens = initialGas.sub(
            gasleft()).add(freeBase).div(reimburse.mul(2).sub(freeToken)
        );

        uint256 mintCost = mintBase.add(tokens.mul(mintToken));
        uint256 freeCost = freeBase.add(tokens.mul(freeToken));
        uint256 maxreimburse = tokens.mul(reimburse);

        uint256 efficiency = maxreimburse.mul(tx.gasprice).mul(100).div(
            mintCost.mul(mintPrice).add(freeCost.mul(tx.gasprice))
        );

        if (efficiency > 100) {
            freeGasTokens(tokens);
        }
    }

    /**
    * @dev Helper method to free gas tokens
    */
    function freeGasTokens(uint256 tokens) private {

        uint256 tokensToFree = tokens;
        uint256 safeNumTokens = 0;
        uint256 gas = gasleft();

        if (gas >= 27710) {
            safeNumTokens = gas.sub(27710).div(1148 + 5722 + 150);
		}

        if (tokensToFree > safeNumTokens) {
            tokensToFree = safeNumTokens;
		}

        uint256 gasTokenBal = _gasToken.balanceOf(address(this));

        if (tokensToFree > 0 && gasTokenBal >= tokensToFree) {
            _gasToken.freeUpTo(tokensToFree);
		}

    }

    /**
    * @dev Helper function to transfer tokens to the destination
    * @dev token Address of the token to be transferred
    * @dev destination Recepient of the token
    * @dev amount Amount of tokens to be transferred
    */
    function transferTokens(
        address token,
        address payable destination,
        uint256 amount
    )
        private
    {
        if (token == ETH_ADDRESS) {
            destination.transfer(amount);
        }
        else{
            IERC20(token).safeTransfer(destination, amount);
        }
    }

    /**
    * @dev Helper method to calculate fees
    * @param receivedAmount Received amount of tokens
    */
    function calculateFee(
        address sourceToken,
        uint256 receivedAmount,
        uint256 calleesLength
    )
        private
        view
        returns(uint256)
    {
        uint256 fee = 0;
        if (sourceToken == ETH_ADDRESS && calleesLength == 1){
            return 0;
        }

        else if (sourceToken != ETH_ADDRESS && calleesLength == 2){
            return 0;
        }

        if (_fee > 0) {
            fee = receivedAmount.mul(_fee).div(10000);
        }
        return fee;
    }

    /**
    * @dev Source take from GNOSIS MultiSigWallet
    * @dev https://github.com/gnosis/MultiSigWallet/blob/master/contracts/MultiSigWallet.sol
    */
    function externalCall(
        address destination,
        uint256 value,
        uint256 dataOffset,
        uint dataLength,
        bytes memory data
    )
        private
        returns (bool)
    {
        bool result = false;
        assembly {
            let x := mload(0x40)   // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)

            let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
            result := call(
                sub(gas, 34710),   // 34710 is the value that solidity is currently emitting
                                   // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
                                   // callNewAccountGas (25000, in case the destination address does not exist and needs creating)
                destination,
                value,
                add(d, dataOffset),
                dataLength,        // Size of the input (in bytes) - this is what fixes the padding problem
                x,
                0                  // Output is ignored, therefore the output size is zero
            )
        }
        return result;
    }

    /**
    * @dev Helper function to returns balance of a user for a token
    * @param token Tokend address
    * @param account Account whose balances has to be returned
    */
    function tokenBalance(
        address token,
        address account
    )
        private
        view
        returns(uint256)
    {
        if (token == ETH_ADDRESS) {
            return account.balance;
        } else {
            return IERC20(token).balanceOf(account);
        }
    }
}
/**
 * @dev The contract will allow swap of one token for another across multiple exchanges in one atomic transaction
 * Kyber, Uniswap and Bancor are supported in phase-01
 */
function approve(
    address token,
    address to,
    uint256 amount
)
    external
    onlySelf
{
    require(amount > 0, "Amount should be greater then 0!!");
    //1. Check for valid whitelisted address
    require(
        isWhitelisted(to),
        "AugustusSwapper: Not a whitelisted address!!"
    );

    //2. Check for ETH address
    if (token != ETH_ADDRESS){
        //3. Approve
        IERC20 _token = IERC20(token);
        _token.safeApprove(to, amount);
    }

}

/**
 * @dev Allows this contract to make approve call for a token
 * This method is expected to be called using externalCall method.
 * @param token The address of the token
 * @param to The address of the spender
 * @param amount The amount to be approved
 */