// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

abstract contract ContextMixin {
    function msgSender() internal view returns (address payable sender) {
        if (msg.sender == address(this)) {
            bytes memory array = msg.data;
            uint256 index = msg.data.length;
            assembly {
                // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
                sender := and(
                    mload(add(array, index)),
                    0xffffffffffffffffffffffffffffffffffffffff
                )
            }
        } else {
            sender = payable(msg.sender);
        }
        return sender;
    }
}


// File contracts/ERC721BidStorage.sol

pragma solidity ^0.8.0;

/**
 * @title Interface for contracts conforming to ERC-20
 */
interface ERC20Interface {
    function balanceOf(address from) external view returns (uint256);

    function transferFrom(
        address from,
        address to,
        uint tokens
    ) external returns (bool);

    function allowance(address owner, address spender)
        external
        view
        returns (uint256);
}

/**
 * @title Interface for contracts conforming to ERC-721
 */
interface ERC721Interface {
    function ownerOf(uint256 _tokenId) external view returns (address _owner);

    function transferFrom(
        address _from,
        address _to,
        uint256 _tokenId
    ) external;

    function supportsInterface(bytes4) external view returns (bool);
}

contract ERC721BidStorage {
    // 182 days - 26 weeks - 6 months
    uint256 public constant MAX_BID_DURATION = 182 days;
    uint256 public constant MIN_BID_DURATION = 1 minutes;
    uint256 public constant ONE_MILLION = 1000000;
    bytes4 public constant ERC721_Interface = 0x80ac58cd;
    bytes4 public constant ERC721_Received = 0x150b7a02;
    bytes4 public constant ERC721Composable_ValidateFingerprint = 0x8f9f4b63;
    uint256 public constant FEE_RATE_BASE = 10000;
    uint256 public feeRate;
    address revenueAddress;

    struct Bid {
        // Bid Id
        bytes32 id;
        // Bidder address
        address bidder;
        // ERC721 address
        address tokenAddress;
        // ERC721 token id
        uint256 tokenId;
        // Price for the bid in wei
        uint256 price;
        // Time when this bid ends
        uint256 expiresAt;
        // ERC20 contract Address
        address erc20Address;
    }

    // MANA token
    // ERC20Interface public ERC20TOKENADDRESS;

    // Bid by token address => token id => bid index => bid
    mapping(address => mapping(uint256 => mapping(uint256 => Bid)))
        internal bidsByToken;
    // Bid count by token address => token id => bid counts
    mapping(address => mapping(uint256 => uint256)) public bidCounterByToken;
    // Index of the bid at bidsByToken mapping by bid id => bid index
    mapping(bytes32 => uint256) public bidIndexByBidId;
    // Bid id by token address => token id => bidder address => bidId
    mapping(address => mapping(uint256 => mapping(address => bytes32)))
        public bidIdByTokenAndBidder;
    // Check if ERC20 token is whitelisted
    mapping(address => bool) isERC20Whitelisted;

    // EVENTS
    event BidCreated(
        bytes32 _id,
        address indexed _tokenAddress,
        uint256 indexed _tokenId,
        address indexed _bidder,
        uint256 _price,
        uint256 _expiresAt,
        address erc20Address
    );

    event BidAccepted(
        bytes32 _id,
        address indexed _tokenAddress,
        uint256 indexed _tokenId,
        address _bidder,
        address indexed _seller,
        uint256 _price,
        uint256 _fee
    );

    event BidCancelled(
        bytes32 _id,
        address indexed _tokenAddress,
        uint256 indexed _tokenId,
        address indexed _bidder
    );
}


// File @openzeppelin/contracts/utils/Address.sol@v4.8.0


// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}


// File @openzeppelin/contracts/utils/Context.sol@v4.8.0


// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}


// File @openzeppelin/contracts/access/Ownable.sol@v4.8.0


// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "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 {
        _transferOwnership(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");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}


// File contracts/LooBrOffers.sol

pragma solidity ^0.8.0;




contract LooBrOffers is Ownable, ERC721BidStorage {
    using Address for address;

    /**
     * @dev Constructor of the contract.
     * @param _owner - owner
     */
    constructor(address _owner, uint256 _feeRate, address _revenueAddress) {
        // Set owner
        transferOwnership(_owner);
        feeRate = _feeRate;
        revenueAddress = _revenueAddress;
    }

    /**
     * @dev Modifier for checking if provided ERC20 contract is whitelisted, fails if not.
     * @param _erc20ContractAddress - address of the ERC20 token
     */
    modifier checkERC20Whitelist(address _erc20ContractAddress) {
        require(
            isERC20Whitelisted[_erc20ContractAddress],
            "LooBr: Contract address isn't whitelisted"
        );
        _;
    }

    /**
     * @dev Whitelist or Blacklist ERC20 contract.
     * @param _erc20ContractAddress - address of the ERC20 token
     * @param _toggler - bool set true to whitelist and false to blacklist ERC20 Token
     */
    function toggleContractWhitelist(
        address _erc20ContractAddress,
        bool _toggler
    ) public onlyOwner {
        require(
            _erc20ContractAddress != address(0),
            "LooBr: Invalid wallet address"
        );
        isERC20Whitelisted[_erc20ContractAddress] = _toggler;
    }

    /**
     * @dev Place a bid for an ERC721 token.
     * @param _tokenAddress - address of the ERC721 token
     * @param _tokenId - uint256 of the token id
     * @param _price - uint256 of the price for the bid
     * @param _duration - uint256 of the duration in seconds for the bid
     */
    function placeBid(
        address _tokenAddress,
        uint256 _tokenId,
        uint256 _price,
        uint256 _duration,
        address _erc20Address
    ) public checkERC20Whitelist(_erc20Address) returns (bytes32) {
        return
            _placeBid(
                _tokenAddress,
                _tokenId,
                _price,
                _duration,
                _erc20Address
            );
    }

    function _placeBid(
        address _tokenAddress,
        uint256 _tokenId,
        uint256 _price,
        uint256 _duration,
        address _erc20Address
    ) private returns (bytes32) {
        _requireERC721(_tokenAddress);
        address sender = _msgSender();
        require(_price > 0, "ERC721Bid#_placeBid: PRICE_MUST_BE_GT_0");
        _requireBidderBalance(sender, _price, _erc20Address);
        require(
            _duration >= MIN_BID_DURATION,
            "ERC721Bid#_placeBid: DURATION_MUST_BE_GTE_MIN_BID_DURATION"
        );
        require(
            _duration <= MAX_BID_DURATION,
            "ERC721Bid#_placeBid: DURATION_MUST_BE_LTE_MAX_BID_DURATION"
        );
        ERC721Interface token = ERC721Interface(_tokenAddress);
        address tokenOwner = token.ownerOf(_tokenId);
        require(
            tokenOwner != address(0) && tokenOwner != sender,
            "ERC721Bid#_placeBid: ALREADY_OWNED_TOKEN"
        );
        uint256 expiresAt = block.timestamp + _duration;
        bytes32 bidId = keccak256(
            abi.encodePacked(
                block.timestamp,
                sender,
                _tokenAddress,
                _tokenId,
                _price,
                _duration
            )
        );
        uint256 bidIndex;
        if (_bidderHasABid(_tokenAddress, _tokenId, sender)) {
            bytes32 oldBidId;
            (bidIndex, oldBidId, , , ) = getBidByBidder(
                _tokenAddress,
                _tokenId,
                sender
            );
            // Delete old bid reference
            delete bidIndexByBidId[oldBidId];
        } else {
            // Use the bid counter to assign the index if there is not an active bid.
            bidIndex = bidCounterByToken[_tokenAddress][_tokenId];
            // Increase bid counter
            bidCounterByToken[_tokenAddress][_tokenId]++;
        }
        // Set bid references
        bidIdByTokenAndBidder[_tokenAddress][_tokenId][sender] = bidId;
        bidIndexByBidId[bidId] = bidIndex;
        // Save Bid
        bidsByToken[_tokenAddress][_tokenId][bidIndex] = Bid({
            id: bidId,
            bidder: sender,
            tokenAddress: _tokenAddress,
            tokenId: _tokenId,
            price: _price,
            expiresAt: expiresAt,
            erc20Address: _erc20Address
        });
        emit BidCreated(
            bidId,
            _tokenAddress,
            _tokenId,
            sender,
            _price,
            expiresAt,
            _erc20Address
        );
        return bidId;
    }

    // function _acceptBid(address _tokenAddress, uint256 _tokenId, address bidder) public {
    //     require(_bidderHasABid(_tokenAddress, _tokenId, bidder), "Bid not found");

    // }

    /**
     * @dev Used as the only way to accept a bid.
     * The token owner should send the token to this contract using safeTransferFrom.
     * The last parameter (bytes) should be the bid id.
     * @notice  The ERC721 smart contract calls this function on the recipient
     * after a `safetransfer`. This function MAY throw to revert and reject the
     * transfer. Return of other than the magic value MUST result in the
     * transaction being reverted.
     * Note:
     * Contract address is always the message sender.
     * This method should be seen as 'acceptBid'.
     * It validates that the bid id matches an active bid for the bid token.
     * @param _tokenId The NFT identifier which is being transferred
     * @param _bidId Additional data with no specified format
     */
    function acceptBid(
        address _tokenAddress,
        uint256 _tokenId,
        bytes32 _bidId
    ) public {
        uint256 bidIndex = bidIndexByBidId[_bidId];
        Bid memory bid = _getBid(_tokenAddress, _tokenId, bidIndex);
        // Check if the bid is valid.
        require(
            // solium-disable-next-line operator-whitespace
            bid.id == _bidId && bid.expiresAt >= block.timestamp,
            "ERC721Bid#onERC721Received: INVALID_BID"
        );
        address bidder = bid.bidder;
        uint256 price = bid.price;
        address _erc20Address = bid.erc20Address;
        // Check if bidder has funds
        _requireBidderBalance(bidder, price, _erc20Address);
        // Delete bid references from contract storage
        delete bidsByToken[_tokenAddress][_tokenId][bidIndex];
        delete bidIndexByBidId[_bidId];
        delete bidIdByTokenAndBidder[_tokenAddress][_tokenId][bidder];
        // Reset bid counter to invalidate other bids placed for the token
        delete bidCounterByToken[_tokenAddress][_tokenId];
        uint256 fee = (price * feeRate) / FEE_RATE_BASE;

        uint256 priceAfterFee = price - fee;

        // Transfer ERC20 from bidder to seller
        require(
            ERC20Interface(_erc20Address).transferFrom(
                bidder,
                msg.sender,
                priceAfterFee
            ),
            "ERC721Bid#onERC721Received:: TRANSFER_AMOUNT_TO_TOKEN_OWNER_FAILED"
        );
        require(
            ERC20Interface(_erc20Address).transferFrom(
                bidder,
                revenueAddress,
                fee
            ),
            "ERC721Bid#onERC721Received:: TRANSFER_AMOUNT_TO_MARKETPLACE_FAILED"
        );
        // Transfer token to bidder
        ERC721Interface(_tokenAddress).transferFrom(
            msg.sender,
            bidder,
            _tokenId
        );
        emit BidAccepted(
            _bidId,
            msg.sender,
            _tokenId,
            bidder,
            msg.sender,
            price,
            fee
        );
    }

    /// Check base function definition
    // function _processFee(uint256 price) internal {
    //     uint256 fee = (price * feeRate) / FEE_RATE_BASE;
    //     uint256 revenue = fee;
    //     ERC20TOKENADDRESS.safeTransferFrom(mrToken, msg.sender, mrConfig.getRevenueAddress(), revenue);
    //     revenueAmount += revenue;
    // }
    /**
     * @dev Remove expired bids
     * @param _tokenAddresses - address[] of the ERC721 tokens
     * @param _tokenIds - uint256[] of the token ids
     * @param _bidders - address[] of the bidders
     */
    function removeExpiredBids(
        address[] memory _tokenAddresses,
        uint256[] memory _tokenIds,
        address[] memory _bidders
    ) public {
        uint256 loopLength = _tokenAddresses.length;
        require(
            loopLength == _tokenIds.length && loopLength == _bidders.length,
            "ERC721Bid#removeExpiredBids: LENGHT_MISMATCH"
        );
        for (uint256 i = 0; i < loopLength; i++) {
            _removeExpiredBid(_tokenAddresses[i], _tokenIds[i], _bidders[i]);
        }
    }

    /**
     * @dev Remove expired bid
     * @param _tokenAddress - address of the ERC721 token
     * @param _tokenId - uint256 of the token id
     * @param _bidder - address of the bidder
     */
    function _removeExpiredBid(
        address _tokenAddress,
        uint256 _tokenId,
        address _bidder
    ) internal {
        (
            uint256 bidIndex,
            bytes32 bidId,
            ,
            ,
            uint256 expiresAt
        ) = getBidByBidder(_tokenAddress, _tokenId, _bidder);
        require(
            expiresAt < block.timestamp,
            "ERC721Bid#_removeExpiredBid: BID_NOT_EXPIRED"
        );
        _cancelBid(bidIndex, bidId, _tokenAddress, _tokenId, _bidder);
    }

    /**
     * @dev Cancel a bid for an ERC721 token
     * @param _tokenAddress - address of the ERC721 token
     * @param _tokenId - uint256 of the token id
     */
    function cancelBid(address _tokenAddress, uint256 _tokenId) public {
        address sender = _msgSender();
        // Get active bid
        (uint256 bidIndex, bytes32 bidId, , , ) = getBidByBidder(
            _tokenAddress,
            _tokenId,
            sender
        );
        _cancelBid(bidIndex, bidId, _tokenAddress, _tokenId, sender);
    }

    /**
     * @dev Cancel a bid for an ERC721 token
     * @param _bidIndex - uint256 of the index of the bid
     * @param _bidId - bytes32 of the bid id
     * @param _tokenAddress - address of the ERC721 token
     * @param _tokenId - uint256 of the token id
     * @param _bidder - address of the bidder
     */
    function _cancelBid(
        uint256 _bidIndex,
        bytes32 _bidId,
        address _tokenAddress,
        uint256 _tokenId,
        address _bidder
    ) internal {
        // Delete bid references
        delete bidIndexByBidId[_bidId];
        delete bidIdByTokenAndBidder[_tokenAddress][_tokenId][_bidder];
        // Check if the bid is at the end of the mapping
        uint256 lastBidIndex = bidCounterByToken[_tokenAddress][_tokenId] - 1;
        if (lastBidIndex != _bidIndex) {
            // Move last bid to the removed place
            Bid storage lastBid = bidsByToken[_tokenAddress][_tokenId][
                lastBidIndex
            ];
            bidsByToken[_tokenAddress][_tokenId][_bidIndex] = lastBid;
            bidIndexByBidId[lastBid.id] = _bidIndex;
        }
        // Delete empty index
        delete bidsByToken[_tokenAddress][_tokenId][lastBidIndex];
        // Decrease bids counter
        bidCounterByToken[_tokenAddress][_tokenId]--;
        // emit BidCancelled event
        emit BidCancelled(_bidId, _tokenAddress, _tokenId, _bidder);
    }

    /**
     * @dev Check if the bidder has a bid for an specific token.
     * @param _tokenAddress - address of the ERC721 token
     * @param _tokenId - uint256 of the token id
     * @param _bidder - address of the bidder
     * @return bool whether the bidder has an active bid
     */
    function _bidderHasABid(
        address _tokenAddress,
        uint256 _tokenId,
        address _bidder
    ) internal view returns (bool) {
        bytes32 bidId = bidIdByTokenAndBidder[_tokenAddress][_tokenId][_bidder];
        uint256 bidIndex = bidIndexByBidId[bidId];
        // Bid index should be inside bounds
        if (bidIndex < bidCounterByToken[_tokenAddress][_tokenId]) {
            Bid memory bid = bidsByToken[_tokenAddress][_tokenId][bidIndex];
            return bid.bidder == _bidder;
        }
        return false;
    }

    /**
     * @dev Get the active bid id and index by a bidder and an specific token.
     * @notice If the bidder has not a valid bid, the transaction will be reverted.
     * @param _tokenAddress - address of the ERC721 token
     * @param _tokenId - uint256 of the token id
     * @param _bidder - address of the bidder
     * @return bidIndex - uint256 of the bid index to be used within bidsByToken mapping
     * @return bidId - bytes32 of the bid id
     * @return bidder - address of the bidder address
     * @return price - uint256 of the bid price
     * @return expiresAt - uint256 of the expiration time
     */
    function getBidByBidder(
        address _tokenAddress,
        uint256 _tokenId,
        address _bidder
    )
        public
        view
        returns (
            uint256 bidIndex,
            bytes32 bidId,
            address bidder,
            uint256 price,
            uint256 expiresAt
        )
    {
        bidId = bidIdByTokenAndBidder[_tokenAddress][_tokenId][_bidder];
        bidIndex = bidIndexByBidId[bidId];
        (bidId, bidder, price, expiresAt) = getBidByToken(
            _tokenAddress,
            _tokenId,
            bidIndex
        );
        if (_bidder != bidder) {
            revert(
                "ERC721Bid#getBidByBidder: BIDDER_HAS_NOT_ACTIVE_BIDS_FOR_TOKEN"
            );
        }
    }

    /**
     * @dev Get an ERC721 token bid by index
     * @param _tokenAddress - address of the ERC721 token
     * @param _tokenId - uint256 of the token id
     * @param _index - uint256 of the index
     * @return bytes32 of the bid id
     * @return address of the bidder address
     * @return uint256 of the bid price
     * @return uint256 of the expiration time
     */
    function getBidByToken(
        address _tokenAddress,
        uint256 _tokenId,
        uint256 _index
    ) public view returns (bytes32, address, uint256, uint256) {
        Bid memory bid = _getBid(_tokenAddress, _tokenId, _index);
        return (bid.id, bid.bidder, bid.price, bid.expiresAt);
    }

    /**
     * @dev Get the active bid id and index by a bidder and an specific token.
     * @notice If the index is not valid, it will revert.
     * @param _tokenAddress - address of the ERC721 token
     * @param _tokenId - uint256 of the index
     * @param _index - uint256 of the index
     * @return Bid
     */
    function _getBid(
        address _tokenAddress,
        uint256 _tokenId,
        uint256 _index
    ) internal view returns (Bid memory) {
        require(
            _index < bidCounterByToken[_tokenAddress][_tokenId],
            "ERC721Bid#_getBid: INVALID_INDEX"
        );
        return bidsByToken[_tokenAddress][_tokenId][_index];
    }

    /**
     * @dev Convert bytes to bytes32
     * @param _data - bytes
     * @return bytes32
     */
    function _bytesToBytes32(
        bytes memory _data
    ) internal pure returns (bytes32) {
        require(
            _data.length == 32,
            "ERC721Bid#_bytesToBytes32: DATA_LENGHT_SHOULD_BE_32"
        );
        bytes32 bidId;
        // solium-disable-next-line security/no-inline-assembly
        assembly {
            bidId := mload(add(_data, 0x20))
        }
        return bidId;
    }

    /**
     * @dev Check if the token has a valid ERC721 implementation
     * @param _tokenAddress - address of the token
     */
    function _requireERC721(address _tokenAddress) internal view {
        require(
            _tokenAddress.isContract(),
            "ERC721Bid#_requireERC721: ADDRESS_NOT_A_CONTRACT"
        );
        ERC721Interface token = ERC721Interface(_tokenAddress);
        require(
            token.supportsInterface(ERC721_Interface),
            "ERC721Bid#_requireERC721: INVALID_CONTRACT_IMPLEMENTATION"
        );
    }

    /**
     * @dev Check if the bidder has balance and the contract has enough allowance
     * to use bidder MANA on his belhalf
     * @param _bidder - address of bidder
     * @param _amount - uint256 of amount
     */
    function _requireBidderBalance(
        address _bidder,
        uint256 _amount,
        address _erc20Address
    ) internal view {
        require(
            ERC20Interface(_erc20Address).balanceOf(_bidder) >= _amount,
            "ERC721Bid#_requireBidderBalance: INSUFFICIENT_FUNDS"
        );
        require(
            ERC20Interface(_erc20Address).allowance(_bidder, address(this)) >=
                _amount,
            "ERC721Bid#_requireBidderBalance: CONTRACT_NOT_AUTHORIZED"
        );
    }
}