// Contract: LocalCryptosETHEscrows
// Target function: function doBuyerCancel(
 "r" component
    /// @param _s Signature "s" component
    /// @param _buyerPercent What % should be distributed to the buyer (this is usually 0 or 100)
    function resolveDispute(
        bytes16 _tradeID,
        address payable _seller,
        address payable _buyer,
        uint256 _value,
        uint16 _fee,
        uint8 _v,
        bytes32 _r,
        bytes32 _s,
        uint8 _buyerPercent
    ) external onlyArbitrator {
        address _signature = recoverAddress(keccak256(abi.encodePacked(
            _tradeID,
            INSTRUCTION_RESOLVE
        )), _v, _r, _s);
        require(_signature == _buyer || _signature == _seller, "Must be buyer or seller");

        Escrow memory _escrow;
        bytes32 _tradeHash;
        (_escrow, _tradeHash) = getEscrowAndHash(_tradeID, _seller, _buyer, _value, _fee);
        require(_escrow.exists, "Escrow does not exist");
        require(_buyerPercent <= 100, "_buyerPercent must be 100 or lower");

        uint256 _totalFees = _escrow.totalGasFeesSpentByRelayer + (GAS_doResolveDispute * uint128(tx.gasprice));
        require(_value - _totalFees <= _value, "Overflow error"); // Prevent underflow
        feesAvailableForWithdraw += _totalFees; // Add the the pot for localethereum to withdraw

        delete escrows[_tradeHash];
        emit DisputeResolved(_tradeHash);
        if (_buyerPercent > 0)
          payable(_buyer).transfer((_value - _totalFees) * _buyerPercent / 100);
        if (_buyerPercent < 100)
          payable(_seller).transfer((_value - _totalFees) * (100 - _buyerPercent) / 100);
    }

    /// @notice Release ether in escrow to the buyer. Direct call option.
    /// @param _tradeID Escrow "tradeID" parameter
    /// @param _seller Escrow "seller" parameter
    /// @param _buyer Escrow "buyer" parameter
    /// @param _value Escrow "value" parameter
    /// @param _fee Escrow "fee parameter
    /// @return bool
    function release(
        bytes16 _tradeID,
        address _seller,
        address payable _buyer,
        uint256 _value,
        uint16 _fee
    ) external returns (bool) {
        require(msg.sender == _seller, "Must be seller");
        return doRelease(_tradeID, _seller, _buyer, _value, _fee, 0);
    }

    /// @notice Disable the seller from cancelling (i.e. "mark as paid"). Direct call option.
    /// @param _tradeID Escrow "tradeID" parameter
    /// @param _seller Escrow "seller" parameter
    /// @param _buyer Escrow "buyer" parameter
    /// @param _value Escrow "value" parameter
    /// @param _fee Escrow "fee parameter
    /// @return bool
    function disableSellerCancel(
        bytes16 _tradeID,
        address _seller,
        address _buyer,
        uint256 _value,
        uint16 _fee
    ) external returns (bool) {
        require(msg.sender == _buyer, "Must be buyer");
        return doDisableSellerCancel(_tradeID, _seller, _buyer, _value, _fee, 0);
    }

    /// @notice Cancel the escrow as a buyer. Direct call option.
    /// @param _tradeID Escrow "tradeID" parameter
    /// @param _seller Escrow "seller" parameter
    /// @param _buyer Escrow "buyer" parameter
    /// @param _value Escrow "value" parameter
    /// @param _fee Escrow "fee parameter
    /// @return bool
    function buyerCancel(
      bytes16 _tradeID,
      address payable _seller,
      address _buyer,
      uint256 _value,
      uint16 _fee
    ) external returns (bool) {
        require(msg.sender == _buyer, "Must be buyer");
        return doBuyerCancel(_tradeID, _seller, _buyer, _value, _fee, 0);
    }

    /// @notice Cancel the escrow as a seller. Direct call option.
    /// @param _tradeID Escrow "tradeID" parameter
    /// @param _seller Escrow "seller" parameter
    /// @param _buyer Escrow "buyer" parameter
    /// @param _value Escrow "value" parameter
    /// @param _fee Escrow "fee parameter
    /// @return bool
    function sellerCancel(
        bytes16 _tradeID,
        address payable _seller,
        address _buyer,
        uint256 _value,
        uint16 _fee
    ) external returns (bool) {
        require(msg.sender == _seller, "Must be seller");
        return doSellerCancel(_tradeID, _seller, _buyer, _value, _fee, 0);
    }

    /// @notice Request to cancel as a seller. Direct call option.
    /// @param _tradeID Escrow "tradeID" parameter
    /// @param _seller Escrow "seller" parameter
    /// @param _buyer Escrow "buyer" parameter
    /// @param _value Escrow "value" parameter
    /// @param _fee Escrow "fee parameter
    /// @return bool
    function sellerRequestCancel(
        bytes16 _tradeID,
        address _seller,
        address _buyer,
        uint256 _value,
        uint16 _fee
    ) external returns (bool) {
        require(msg.sender == _seller, "Must be seller");
        return doSellerRequestCancel(_tradeID, _seller, _buyer, _value, _fee, 0);
    }

    uint16 constant GAS_batchRelayBase = 32720;
    /// @notice Relay multiple signed instructions from parties of escrows.
    /// @param _tradeID List of _tradeID values
    /// @param _seller List of _seller values
    /// @param _buyer List of _buyer values
    /// @param _value List of _value values
    /// @param _fee List of _fee values
    /// @param _maximumGasPrice List of _maximumGasPrice values
    /// @param _v List of signature "v" components
    /// @param _r List of signature "r" components
    /// @param _s List of signature "s" components
    /// @param _instructionByte List of _instructionByte values
    /// @return bool List of results
    function batchRelay(
        bytes16[] memory _tradeID,
        address payable[] memory _seller,
        address payable[] memory _buyer,
        uint256[] memory _value,
        uint16[] memory _fee,
        uint128[] memory _maximumGasPrice,
        uint8[] memory _v,
        bytes32[] memory _r,
        bytes32[] memory _s,
        uint8[] memory _instructionByte
    ) public returns (bool[] memory) {
        bool[] memory _results = new bool[](_tradeID.length);
        uint128 _additionalGas = uint128(relayers[msg.sender] == true ? (GAS_batchRelayBase / _tradeID.length) : 0);
        for (uint8 i=0; i<_tradeID.length; i++) {
            _results[i] = relay(
                _tradeID[i],
                _seller[i],
                _buyer[i],
                _value[i],
                _fee[i],
                _maximumGasPrice[i],
                _v[i],
                _r[i],
                _s[i],
                _instructionByte[i],
                _additionalGas
            );
        }
        return _results;
    }

    /// @notice Withdraw fees collected by the contract. Only the owner can call this.
    /// @param _to Address to withdraw fees in to
    /// @param _amount Amount to withdraw
    function withdrawFees(address payable _to, uint256 _amount) onlyOwner external {
        // This check also prevents underflow
        require(_amount <= feesAvailableForWithdraw, "Amount is higher than amount available");
        feesAvailableForWithdraw -= _amount;
        payable(_to).transfer(_amount);
    }

    /// @notice Set the arbitrator to a new address. Only the owner can call this.
    /// @param _newArbitrator Address of the replacement arbitrator
    function setArbitrator(address _newArbitrator) onlyOwner external {
        arbitrator = _newArbitrator;
    }

    /// @notice Change the owner to a new address. Only the owner can call this.
    /// @param _newOwner Address of the replacement owner
    function setOwner(address _newOwner) onlyOwner external {
        owner = _newOwner;
    }

    /// @notice Enable or disable a relayer address. Only the owner can call this.
    /// @param _newRelayer Address of the relayer
    /// @param _enabled Whether the relayer is enabled
    function setRelayer(address _newRelayer, bool _enabled) onlyOwner external {
        relayers[_newRelayer] = _enabled;
    }

    /// @notice Change the inviter to a new address. Only the owner can call this.
    /// @param _newInviterAddress Address of the inviter address
    function setInviterAddress(address _newInviterAddress) onlyOwner external {
        inviterAddress = _newInviterAddress;
    }

    /// @notice Change the requestCancellationMinimumTime. Only the owner can call this.
    /// @param _newRequestCancellationMinimumTime Replacement
    function setRequestCancellationMinimumTime(
        uint32 _newRequestCancellationMinimumTime
    ) onlyOwner external {
        requestCancellationMinimumTime = _newRequestCancellationMinimumTime;
    }

    /// @notice Send ERC20 tokens away. This function allows the owner to withdraw stuck ERC20 tokens.
    /// @param _tokenContract Token contract
    /// @param _transferTo Recipient
    /// @param _value Value
    function transferToken(
        Token _tokenContract,
        address _transferTo,
        uint256 _value
    ) onlyOwner external {
        _tokenContract.transfer(_transferTo, _value);
    }

    /// @notice Send ERC20 tokens away. This function allows the owner to withdraw stuck ERC20 tokens.
    /// @param _tokenContract Token contract
    /// @param _transferTo Recipient
    /// @param _transferFrom Sender
    /// @param _value Value
    function transferTokenFrom(
        Token _tokenContract,
        address _transferTo,
        address _transferFrom,
        uint256 _value
    ) onlyOwner external {
        _tokenContract.transferFrom(_transferTo, _transferFrom, _value);
    }

    /// @notice Send ERC20 tokens away. This function allows the owner to withdraw stuck ERC20 tokens.
    /// @param _tokenContract Token contract
    /// @param _spender Spender address
    /// @param _value Value
    function approveToken(
        Token _tokenContract,
        address _spender,
        uint256 _value
    ) onlyOwner external {
        _tokenContract.approve(_spender, _value);
    }

    /// @notice Relay a signed instruction from a party of an escrow.
    /// @param _tradeID Escrow "tradeID" parameter
    /// @param _seller Escrow "seller" parameter
    /// @param _buyer Escrow "buyer" parameter
    /// @param _value Escrow "value" parameter
    /// @param _fee Escrow "fee parameter
    /// @param _maximumGasPrice Maximum gas price permitted for the relayer (set by the instructor)
    /// @param _v Signature "v" component
    /// @param _r Signature "r" component
    /// @param _s Signature "s" component
    /// @param _additionalGas Additional gas to be deducted after this operation
    /// @return bool
    function relay(
        bytes16 _tradeID,
        address payable _seller,
        address payable _buyer,
        uint256 _value,
        uint16 _fee,
        uint128 _maximumGasPrice,
        uint8 _v,
        bytes32 _r,
        bytes32 _s,
        uint8 _instructionByte,
        uint128 _additionalGas
    ) private returns (bool) {
        address _relayedSender = getRelayedSender(
            _tradeID,
            _instructionByte,
            _maximumGasPrice,
            _v,
            _r,
            _s
        );
        if (_relayedSender == _buyer) {
            // Buyer's instructions:
            if (_instructionByte == INSTRUCTION_SELLER_CANNOT_CANCEL) {
                // Disable seller from cancelling
                return doDisableSellerCancel(_tradeID, _seller, _buyer, _value, _fee, _additionalGas);
            } else if (_instructionByte == INSTRUCTION_BUYER_CANCEL) {
                // Cancel
                return doBuyerCancel(_tradeID, _seller, _buyer, _value, _fee, _additionalGas);
            }
        } else if (_relayedSender == _seller) {
            // Seller's instructions:
            if (_instructionByte == INSTRUCTION_RELEASE) {
                // Release
                return doRelease(_tradeID, _seller, _buyer, _value, _fee, _additionalGas);
            } else if (_instructionByte == INSTRUCTION_SELLER_CANCEL) {
                // Cancel
                return doSellerCancel(_tradeID, _seller, _buyer, _value, _fee, _additionalGas);
            } else if (_instructionByte == INSTRUCTION_SELLER_REQUEST_CANCEL) {
                // Request to cancel
                return doSellerRequestCancel(_tradeID, _seller, _buyer, _value, _fee, _additionalGas);
            }
        }
        return false;
    }

    /// @notice Increase the amount of gas to be charged later on completion of an escrow
    /// @param _tradeHash Trade hash
    /// @param _gas Gas cost
    function increaseGasSpent(bytes32 _tradeHash, uint128 _gas) private {
        escrows[_tradeHash].totalGasFeesSpentByRelayer += _gas * uint128(tx.gasprice);
    }

    /// @notice Transfer the value of an escrow, minus the fees, minus the gas costs incurred by relay
    /// @param _to Recipient address
    /// @param _value Value of the transfer
    /// @param _totalGasFeesSpentByRelayer Total gas fees spent by the relayer
    /// @param _fee Commission in 1/10000ths
    function transferMinusFees(
        address payable _to,
        uint256 _value,
        uint128 _totalGasFeesSpentByRelayer,
        uint16 _fee
    ) private {
        uint256 _totalFees = (_value * _fee / 10000) + _totalGasFeesSpentByRelayer;
        // Prevent underflow
        if(_value - _totalFees > _value) {
            return;
        }
        // Add fees to the pot for localethereum to withdraw
        feesAvailableForWithdraw += _totalFees;
        payable(_to).transfer(_value - _totalFees);
    }

    uint16 constant GAS_doRelease = 12664;
    /// @notice Release escrow to the buyer. This completes it and removes it from the mapping.
    /// @param _tradeID Escrow "tradeID" parameter
    /// @param _seller Escrow "seller" parameter
    /// @param _buyer Escrow "buyer" parameter
    /// @param _value Escrow "value" parameter
    /// @param _fee Escrow "fee parameter
    /// @param _additionalGas Additional gas to be deducted after this operation
    /// @return bool
    function doRelease(
        bytes16 _tradeID,
        address _seller,
        address payable _buyer,
        uint256 _value,
        uint16 _fee,
        uint128 _additionalGas
    ) private returns (bool) {
        Escrow memory _escrow;
        bytes32 _tradeHash;
        (_escrow, _tradeHash) = getEscrowAndHash(_tradeID, _seller, _buyer, _value, _fee);
        if (!_escrow.exists) return false;
        uint128 _gasFees = _escrow.totalGasFeesSpentByRelayer
            + (relayers[msg.sender] == true
                ? (GAS_doRelease + _additionalGas ) * uint128(tx.gasprice)
                : 0
            );
        delete escrows[_tradeHash];
        emit Released(_tradeHash);
        transferMinusFees(_buyer, _value, _gasFees, _fee);
        return true;
    }

    uint16 constant GAS_doDisableSellerCancel = 16568;
    /// @notice Prevents the seller from cancelling an escrow. Used to "mark as paid" by the buyer.
    /// @param _tradeID Escrow "tradeID" parameter
    /// @param _seller Escrow "seller" parameter
    /// @param _buyer Escrow "buyer" parameter
    /// @param _value Escrow "value" parameter
    /// @param _fee Escrow "fee parameter
    /// @param _additionalGas Additional gas to be deducted after this operation
    /// @return bool
    function doDisableSellerCancel(
        bytes16 _tradeID,
        address _seller,
        address _buyer,
        uint256 _value,
        uint16 _fee,
        uint128 _additionalGas
    ) private returns (bool) {
        Escrow memory _escrow;
        bytes32 _tradeHash;
        (_escrow, _tradeHash) = getEscrowAndHash(_tradeID, _seller, _buyer, _value, _fee);
        if (!_escrow.exists) return false;
        if(_escrow.sellerCanCancelAfter == 0) return false;
        escrows[_tradeHash].sellerCanCancelAfter = 0;
        emit SellerCancelDisabled(_tradeHash);
        if (relayers[msg.sender] == true) {
          increaseGasSpent(_tradeHash, GAS_doDisableSellerCancel + _additionalGas);
        }
        return true;
    }

    uint16 constant GAS_doBuyerCancel = 12648;