// File: Context.sol



// SPDX-License-Identifier: MIT

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) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}

// File: Counters.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @title Counters
 * @author Matt Condon (@shrugs)
 * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
 * of elements in a mapping, issuing ERC721 ids, or counting request ids.
 *
 * Include with `using Counters for Counters.Counter;`
 */
library Counters {
    struct Counter {
        // This variable should never be directly accessed by users of the library: interactions must be restricted to
        // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
        // this feature: see https://github.com/ethereum/solidity/issues/4637
        uint256 _value; // default: 0
    }

    function current(Counter storage counter) internal view returns (uint256) {
        return counter._value;
    }

    function increment(Counter storage counter) internal {
        unchecked {
            counter._value += 1;
        }
    }

    function decrement(Counter storage counter) internal {
        uint256 value = counter._value;
        require(value > 0, "Counter: decrement overflow");
        unchecked {
            counter._value = value - 1;
        }
    }
}

// File: ECDSA.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        // Divide the signature in r, s and v variables
        bytes32 r;
        bytes32 s;
        uint8 v;

        // Check the signature length
        // - case 65: r,s,v signature (standard)
        // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
        if (signature.length == 65) {
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            // solhint-disable-next-line no-inline-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
        } else if (signature.length == 64) {
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            // solhint-disable-next-line no-inline-assembly
            assembly {
                let vs := mload(add(signature, 0x40))
                r := mload(add(signature, 0x20))
                s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
                v := add(shr(255, vs), 27)
            }
        } else {
            revert("ECDSA: invalid signature length");
        }

        return recover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
        require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        require(signer != address(0), "ECDSA: invalid signature");

        return signer;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
    }
}

// File: EditionRoyalty.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

library EditionRoyalty {
  struct Royalty {
    address payable account;
    uint256 value;
  }

  struct Info {
    uint256 id;
    uint256 totalSupply;
    Royalty royalty;
  }
}
// File: IAggregatorPrice.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IAggregatorPrice {

  function decimals()
    external
    view
    returns (
      uint8
    );

  function description()
    external
    view
    returns (
      string memory
    );

  function version()
    external
    view
    returns (
      uint256
    );

  // getRoundData and latestRoundData should both raise "No data present"
  // if they do not have data to report, instead of returning unset values
  // which could be misinterpreted as actual reported values.
  function getRoundData(
    uint80 _roundId
  )
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );

  function latestRoundData()
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );

}
// File: IHabitatNFT.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import './EditionRoyalty.sol';

interface IHabitatNFT {
  function mint(
    address account,
    uint256 id,
    uint256 amount,
    EditionRoyalty.Royalty memory editionRoyalty,
    bytes memory data
  ) external;

  function safeTransferFrom(
    address from,
    address to,
    uint256 id,
    uint256 amount,
    bytes memory data
  ) external;
  
  function burn(
    address from,
    uint256 id,
    uint256 amount
    ) external;
}

// File: PrimaryMarketplace.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./ReentrancyGuard.sol";
import "./Context.sol";
import "./Counters.sol";
import "./SafeMath.sol";
import "./ECDSA.sol";

import "./IHabitatNFT.sol";
import "./IAggregatorPrice.sol";
import "./EditionRoyalty.sol";

contract PrimaryMarketplace is ReentrancyGuard, Context {
    using ECDSA for bytes32;
    using SafeMath for uint256;
    using Counters for Counters.Counter;
    Counters.Counter private _itemIds;
    IAggregatorPrice private priceFeed;

    struct Edition {
        uint256 itemId;
        address nftContract;
        uint256 tokenId;
        uint256 totalAmount;
        uint256 availableAmount;
        address payable seller;
        uint256 price;
        uint256 royalty;
    }

    struct Auction {
        bool isAuction;
        bool transfered;
    }

    address payable private owner;

    mapping(uint256 => Edition) private idToEdition;
    mapping(uint256 => Auction) private itemIdToAuction;
    mapping(address => bool) private creatorsWhitelist;

    modifier onlyOwner() {
        require(_msgSender() == owner, "Only Habitat can execute this");
        _;
    }

    modifier onlyOwnerOrCreator() {
        require(
            creatorsWhitelist[_msgSender()] || _msgSender() == owner,
            "Only Habitat and Habitat's creators can execute this"
        );
        _;
    }

    modifier onlyAvailableEdition(uint256 itemId) {
        require(
            idToEdition[itemId].nftContract != address(0),
            "Item doensn't exist"
        );
        _;
    }

    modifier onlyNonClaimableEdition(uint256 itemId) {
        require(idToEdition[itemId].price > 0, "Can't buy this edition");
        _;
    }

    modifier onlyCorrectPriceForEdition(uint256 itemId, uint256 amount) {
        uint256 pricePerItemInUSD = idToEdition[itemId].price;
        uint256 pricePerItem = pricePerItemInUSD.mul(priceInWEI());
        uint256 price = pricePerItem.mul(amount);
        require(
            msg.value >= price,
            "Please submit the asking price in order to complete the purchase"
        );
        _;
    }

    modifier onlyNonAuction(uint256 itemId) {
        require(
            itemIdToAuction[itemId].isAuction == false,
            "Can't buy this edition"
        );
        _;
    }

    modifier onlyAuction(uint256 itemId) {
        require(
            itemIdToAuction[itemId].isAuction == true,
            "This auction edition doesn't exist"
        );
        _;
    }

    modifier onlyActiveAuction(uint256 itemId) {
        require(
            itemIdToAuction[itemId].transfered == false,
            "This auction edition is not active"
        );
        _;
    }

    constructor(address priceAggregatorAddress) {
        owner = payable(msg.sender);
        priceFeed = IAggregatorPrice(priceAggregatorAddress);
    }

    receive() external payable {}

    fallback() external payable {}

    function addCreator(address creator) external onlyOwner {
        creatorsWhitelist[creator] = true;
    }

    function addEdition(
        address nftContract,
        uint256 tokenId,
        uint256 amount,
        uint256 price,
        uint256 royalty,
        bool isHighestBidAuction
    ) external nonReentrant onlyOwnerOrCreator {
        _itemIds.increment();
        uint256 itemId = _itemIds.current();

        EditionRoyalty.Royalty memory editionRoyalty = EditionRoyalty.Royalty(
            payable(_msgSender()),
            royalty
        );

        IHabitatNFT(nftContract).mint(
            _msgSender(),
            tokenId,
            amount,
            editionRoyalty,
            ""
        );

        idToEdition[itemId] = Edition(
            itemId,
            nftContract,
            tokenId,
            amount,
            amount,
            payable(_msgSender()),
            price,
            royalty
        );

        if (isHighestBidAuction == true) {
            itemIdToAuction[itemId] = Auction(true, false);
        }

        emit EditionAdded(
            itemId,
            nftContract,
            tokenId,
            amount,
            _msgSender(),
            price
        );
    }

    function transferEdition(
        uint256 itemId,
        uint256 amount,
        address receiver
    )
        external
        nonReentrant
        onlyOwner
        onlyAvailableEdition(itemId)
        onlyNonAuction(itemId)
    {
        _safeTransfer(itemId, amount, receiver);
        emit EditionTransfered(itemId, receiver);
    }

    function transferAuction(uint256 itemId, address receiver)
        external
        nonReentrant
        onlyOwner
        onlyAuction(itemId)
        onlyActiveAuction(itemId)
    {
        _safeTransfer(itemId, 1, receiver);
        itemIdToAuction[itemId].transfered = true;
        emit AuctionTransfered(itemId, receiver);
    }

    function burnToken(uint256 itemId) external onlyOwnerOrCreator {
        uint256 amount = idToEdition[itemId].availableAmount;
        IHabitatNFT(idToEdition[itemId].nftContract).burn(
            idToEdition[itemId].seller,
            idToEdition[itemId].tokenId,
            amount
        );
        idToEdition[itemId].availableAmount.sub(amount);
        emit BurnedEdition(itemId, amount);
    }

    function itemPrice(uint256 itemId)
        external
        view
        onlyAvailableEdition(itemId)
        returns (uint256)
    {
        uint256 pricePerItemInUSD = idToEdition[itemId].price;
        uint256 pricePerItem = pricePerItemInUSD.mul(priceInWEI());
        return pricePerItem;
    }

    function fetchEditions() external view returns (Edition[] memory) {
        uint256 itemCount = _itemIds.current();
        uint256 currentIndex = 0;
        Edition[] memory items = new Edition[](itemCount);
        for (uint256 i = 0; i < itemCount; i++) {
            Edition memory currentItem = idToEdition[i + 1];
            items[currentIndex] = currentItem;
            currentIndex += 1;
        }
        return items;
    }

    function fetchCreatorEditions(address habitatNFTCreatorAddress)
        external
        view
        returns (Edition[] memory)
    {
        uint256 itemCount = _itemIds.current();
        uint256 resultCount = 0;
        uint256 currentIndex = 0;
        for (uint256 i = 0; i < itemCount; i++) {
            if (idToEdition[i + 1].nftContract == habitatNFTCreatorAddress) {
                resultCount += 1;
            }
        }
        Edition[] memory result = new Edition[](resultCount);
        for (uint256 i = 0; i < itemCount; i++) {
            if (idToEdition[i + 1].nftContract == habitatNFTCreatorAddress) {
                Edition memory currentItem = idToEdition[i + 1];
                result[currentIndex] = currentItem;
                currentIndex += 1;
            }
        }
        return result;
    }

    function buyEdition(uint256 itemId, uint256 amount)
        external
        payable
        nonReentrant
        onlyAvailableEdition(itemId)
        onlyNonAuction(itemId)
        onlyNonClaimableEdition(itemId)
        onlyCorrectPriceForEdition(itemId, amount)
    {
        _safeTransfer(itemId, amount, _msgSender());
        payable(idToEdition[itemId].seller).transfer(msg.value);
        emit EditionBought(itemId, _msgSender(), msg.value);
    }

    function hashTransaction(address account, uint256 price)
        internal
        pure
        returns (bytes32)
    {
        bytes32 dataHash = keccak256(abi.encodePacked(account, price));
        return
            keccak256(
                abi.encodePacked("\x19Ethereum Signed Message:\n32", dataHash)
            );
    }

    function recoverSignerAddress(
        address account,
        uint256 price,
        bytes memory signature
    ) internal pure returns (address) {
        bytes32 hash = hashTransaction(account, price);
        return hash.recover(signature);
    }

    function payForBid(
        uint256 itemId,
        uint256 price,
        bytes memory signature
    ) external payable nonReentrant onlyActiveAuction(itemId) {
        address verifiedSigner = recoverSignerAddress(
            _msgSender(),
            price,
            signature
        );

        require(verifiedSigner == owner, "You chan't buy this");
        require(
            msg.value >= price * priceInWEI(),
            "Please submit the asking price in order to complete the purchase"
        );

        _safeTransfer(itemId, 1, _msgSender());
        itemIdToAuction[itemId].transfered = true;
        payable(idToEdition[itemId].seller).transfer(msg.value);
        emit WinnerPaidForBid(itemId, _msgSender(), msg.value);
    }

    function _safeTransfer(
        uint256 itemId,
        uint256 amount,
        address receiver
    ) internal {
        uint256 availableAmount = idToEdition[itemId].availableAmount;
        require(availableAmount > 0, "Sold out");
        require(availableAmount >= amount, "Not available quantity");
        IHabitatNFT(idToEdition[itemId].nftContract).safeTransferFrom(
            idToEdition[itemId].seller,
            receiver,
            idToEdition[itemId].tokenId,
            amount,
            ""
        );
        idToEdition[itemId].availableAmount -= amount;
    }

    function _priceOfETH() private view returns (uint256) {
        (
            uint80 roundID,
            int256 price,
            uint256 startedAt,
            uint256 timeStamp,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();
        (roundID, startedAt, timeStamp, answeredInRound);
        return uint256(price);
    }

    function priceInWEI() public view returns (uint256) {
        return uint256(10**18 / uint256(_priceOfETH() / 10**_decimals()));
    }

    function _decimals() private view returns (uint256) {
        uint256 decimals = uint256(priceFeed.decimals());
        return decimals;
    }

    event EditionAdded(
        uint256 indexed itemId,
        address indexed nftContract,
        uint256 indexed tokenId,
        uint256 amount,
        address seller,
        uint256 price
    );
    event EditionBought(
        uint256 indexed itemId,
        address indexed receiver,
        uint256 price
    );
    event EditionTransfered(uint256 indexed itemId, address indexed receiver);
    event AuctionTransfered(uint256 indexed itemId, address indexed receiver);
    event BurnedEdition(uint256 indexed itemId, uint256 amount);
    event WinnerPaidForBid(
        uint256 indexed itemId,
        address indexed winner,
        uint256 indexed bidAmount
    );
}
// File: ReentrancyGuard.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor () {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and make it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}

// File: SafeMath.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.

/**
 * @dev Wrappers over Solidity's arithmetic operations.
 *
 * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
 * now has built in overflow checking.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the substraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        return a + b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        return a * b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator.
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b <= a, errorMessage);
            return a - b;
        }
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a / b;
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a % b;
        }
    }
}