// Contract: LocalCryptosETHEscrows
// Target function: function buyerCancel(
/**
   Copyright (c) 2021 LocalCryptos.com

   Licensed under the Apache License, Version 2.0 (the “License”);
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an “AS IS” BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;

abstract contract Token {
    function transfer(address _to, uint _value) public virtual returns (bool success);
    function transferFrom(address _from, address _to, uint _value) public virtual returns (bool success);
    function virtualapprove(address _spender, uint _value) public virtual returns (bool success);
    function approve(address spender, uint256 value) public virtual returns (bool);
}

/// @title LocalCryptos ETH Escrows
/// @author LocalCryptos
contract LocalCryptosETHEscrows {
    /***********************
    +   Global settings   +
    ***********************/

    // Address of the arbitrator (currently always localethereum staff)
    address public arbitrator;
    // Address of the owner (who can withdraw collected fees)
    address public owner;
    address public inviterAddress;
    // Addresses of the relayers (which addresses are allowed to forward signed instructions from parties)
    mapping (address => bool) public relayers;

    uint32 public requestCancellationMinimumTime;
    // Cumulative balance of collected fees
    uint256 public feesAvailableForWithdraw;

    /***********************
    +  Instruction types  +
    ***********************/

    // Called when the buyer marks payment as sent. Locks funds in escrow
    uint8 constant INSTRUCTION_SELLER_CANNOT_CANCEL = 0x01;
    // Buyer cancelling
    uint8 constant INSTRUCTION_BUYER_CANCEL = 0x02;
    // Seller cancelling
    uint8 constant INSTRUCTION_SELLER_CANCEL = 0x03;
    // Seller requesting to cancel. Begins a window for buyer to object
    uint8 constant INSTRUCTION_SELLER_REQUEST_CANCEL = 0x04;
    // Seller releasing funds to the buyer
    uint8 constant INSTRUCTION_RELEASE = 0x05;
    // Either party permitting the arbitrator to resolve a dispute
    uint8 constant INSTRUCTION_RESOLVE = 0x06;

    /***********************
    +       Events        +
    ***********************/

    event Created(bytes32 indexed _tradeHash);
    event SellerCancelDisabled(bytes32 indexed _tradeHash);
    event SellerRequestedCancel(bytes32 indexed _tradeHash);
    event CancelledBySeller(bytes32 indexed _tradeHash);
    event CancelledByBuyer(bytes32 indexed _tradeHash);
    event Released(bytes32 indexed _tradeHash);
    event DisputeResolved(bytes32 indexed _tradeHash);

    struct Escrow {
        // So we know the escrow exists
        bool exists;
        // This is the timestamp in whic hthe seller can cancel the escrow after.
        // It has two special values:
        // 0 : Permanently locked by the buyer (i.e. marked as paid; the seller can never cancel)
        // 1 : The seller can only request to cancel, which will change this value to a timestamp.
        //     This option is avaialble for complex trade terms such as cash-in-person where a
        //     payment window is inappropriate
        uint32 sellerCanCancelAfter;
        // Cumulative cost of gas incurred by the relayer. This amount will be refunded to the owner
        // in the way of fees once the escrow has completed
        uint128 totalGasFeesSpentByRelayer;
    }

    // Mapping of active trades. The key here is a hash of the trade proprties
    mapping (bytes32 => Escrow) public escrows;

    modifier onlyOwner() {
        require(msg.sender == owner, "Must be owner");
        _;
    }

    modifier onlyArbitrator() {
        require(msg.sender == arbitrator, "Must be arbitrator");
        _;
    }

    /// @notice Initialize the contract.
    constructor() {
        owner = msg.sender;
        arbitrator = msg.sender;
        inviterAddress = msg.sender;
        requestCancellationMinimumTime = 0 seconds;
    }

    /// @notice Create and fund a new escrow.
    /// @param _tradeID The unique ID of the trade, generated by localethereum.com
    /// @param _seller The selling party
    /// @param _buyer The buying party
    /// @param _value The amount of the escrow, exclusive of the fee
    /// @param _fee Localethereum's commission in 1/10000ths
    /// @param _paymentWindowInSeconds The time in seconds from escrow creation that the seller can cancel after
    /// @param _expiry This transaction must be created before this time
    /// @param _v Signature "v" component
    /// @param _r Signature "r" component
    /// @param _s Signature "s" component
    function createEscrow(
        bytes16 _tradeID,
        address _seller,
        address _buyer,
        uint256 _value,
        uint16 _fee,
        uint32 _paymentWindowInSeconds,
        uint32 _expiry,
        uint8 _v,
        bytes32 _r,
        bytes32 _s
    ) payable external {
        // The trade hash is created by tightly-concatenating and hashing properties of the trade.
        // This hash becomes the identifier of the escrow, and hence all these variables must be
        // supplied on future contract calls
        bytes32 _tradeHash = keccak256(abi.encodePacked(_tradeID, _seller, _buyer, _value, _fee));
        // Require that trade does not already exist
        require(!escrows[_tradeHash].exists, "Trade already exists");
        // A signature (v, r and s) must come from localethereum to open an escrow
        bytes32 _invitationHash = keccak256(abi.encodePacked(
            _tradeHash,
            _paymentWindowInSeconds,
            _expiry
        ));
        require(recoverAddress(_invitationHash, _v, _r, _s) == inviterAddress, "Invitation signature was not valid");
        // These signatures come with an expiry stamp
        require(block.timestamp < _expiry, "Signature has expired");
        // Check transaction value against signed _value and make sure is not 0
        require(msg.value == _value && msg.value > 0, "Incorrect ether sent");
        uint32 _sellerCanCancelAfter = _paymentWindowInSeconds == 0
            ? 1
            : uint32(block.timestamp) + _paymentWindowInSeconds;
        // Add the escrow to the public mapping
        escrows[_tradeHash] = Escrow(true, _sellerCanCancelAfter, 0);
        emit Created(_tradeHash);
    }

    uint16 constant GAS_doResolveDispute = 45368;
    /// @notice Called by the arbitrator to resolve a dispute. Requires a signature from either party.
    /// @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 _v Signature "v" component
    /// @param _r Signature "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);
    }