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"
        );
    }
}
[{"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"uint256","name":"_feeRate","type":"uint256"},{"internalType":"address","name":"_revenueAddress","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"_id","type":"bytes32"},{"indexed":true,"internalType":"address","name":"_tokenAddress","type":"address"},{"indexed":true,"internalType":"uint256","name":"_tokenId","type":"uint256"},{"indexed":false,"internalType":"address","name":"_bidder","type":"address"},{"indexed":true,"internalType":"address","name":"_seller","type":"address"},{"indexed":false,"internalType":"uint256","name":"_price","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_fee","type":"uint256"}],"name":"BidAccepted","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"_id","type":"bytes32"},{"indexed":true,"internalType":"address","name":"_tokenAddress","type":"address"},{"indexed":true,"internalType":"uint256","name":"_tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"_bidder","type":"address"}],"name":"BidCancelled","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"_id","type":"bytes32"},{"indexed":true,"internalType":"address","name":"_tokenAddress","type":"address"},{"indexed":true,"internalType":"uint256","name":"_tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"_bidder","type":"address"},{"indexed":false,"internalType":"uint256","name":"_price","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_expiresAt","type":"uint256"},{"indexed":false,"internalType":"address","name":"erc20Address","type":"address"}],"name":"BidCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"inputs":[],"name":"ERC721Composable_ValidateFingerprint","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ERC721_Interface","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ERC721_Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"FEE_RATE_BASE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_BID_DURATION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MIN_BID_DURATION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ONE_MILLION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_tokenId","type":"uint256"},{"internalType":"bytes32","name":"_bidId","type":"bytes32"}],"name":"acceptBid","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"bidCounterByToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"address","name":"","type":"address"}],"name":"bidIdByTokenAndBidder","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"bidIndexByBidId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"cancelBid","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"feeRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_tokenId","type":"uint256"},{"internalType":"address","name":"_bidder","type":"address"}],"name":"getBidByBidder","outputs":[{"internalType":"uint256","name":"bidIndex","type":"uint256"},{"internalType":"bytes32","name":"bidId","type":"bytes32"},{"internalType":"address","name":"bidder","type":"address"},{"internalType":"uint256","name":"price","type":"uint256"},{"internalType":"uint256","name":"expiresAt","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_tokenId","type":"uint256"},{"internalType":"uint256","name":"_index","type":"uint256"}],"name":"getBidByToken","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_tokenId","type":"uint256"},{"internalType":"uint256","name":"_price","type":"uint256"},{"internalType":"uint256","name":"_duration","type":"uint256"},{"internalType":"address","name":"_erc20Address","type":"address"}],"name":"placeBid","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"_tokenAddresses","type":"address[]"},{"internalType":"uint256[]","name":"_tokenIds","type":"uint256[]"},{"internalType":"address[]","name":"_bidders","type":"address[]"}],"name":"removeExpiredBids","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_erc20ContractAddress","type":"address"},{"internalType":"bool","name":"_toggler","type":"bool"}],"name":"toggleContractWhitelist","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"}]