Skip to content
Verified contractExactMIT

ERC1155Marketplace

Address0x337d172a6bf68e8d48960637db71f2ebf4f2b7fa
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.31

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.31+commit.fd3a2265
Language
solidity
Optimization
No
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
24,474,556
Creation transaction
0x48d17fd85c…aaec074aa9

MarketTest.sol

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

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; // Only IERC1155, not ERC1155Supply
import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

contract ERC1155Marketplace is Ownable, ReentrancyGuard {

    constructor(address initialOwner) Ownable(initialOwner) {}

    struct Listing {
        address nftContract;
        uint256 tokenId;
        bool forSale;
        address seller;
        uint256 amount; // Quantity of tokens available for sale
        uint256 unitPrice; // Price per unit (in wei)
    }

    struct Offer {
        address maker;
        address nftContract;
        uint256 tokenId;
        uint256 amount;
        bool accepted;
    }

    mapping(bytes32 => Listing) public listings;
    mapping(address => mapping(uint256 => Offer)) public offers;

    event NFTListed(
        address indexed seller,
        address indexed nftContract,
        uint256 indexed tokenId,
        uint256 amount,
        uint256 unitPrice
    );

    event NFTHarvested(
        address indexed buyer,
        address indexed seller,
        address indexed nftContract,
        uint256 tokenId,
        uint256 amountBought,
        uint256 totalAmountPaid
    );

    event OfferMade(
        address indexed maker,
        address indexed nftContract,
        uint256 tokenId,
        uint256 amount,
        uint256 unitPrice
    );

    event OfferAccepted(
        address indexed seller,
        address indexed buyer,
        address indexed nftContract,
        uint256 tokenId,
        uint256 amountBought,
        uint256 totalAmountPaid
    );

    // Prevents listing or buying own items
    modifier notSelf(address _seller) {
        require(_seller != msg.sender, "Cannot list/offer your own item");
        _;
    }

    function listNFT(
        address _nftContract,
        uint256 _tokenId,
        uint256 _amount,
        uint256 _unitPrice
    ) external notSelf(msg.sender) nonReentrant {
        require(_amount > 0, "Amount must be greater than zero");
        require(_unitPrice > 0, "Unit price must be greater than zero");

        IERC1155 nft = IERC1155(_nftContract);
        
        // Check that the contract supports ERC-1155
        try nft.supportsInterface(0xd9b67a26) returns (bool supported) {
            require(supported, "Address does not implement ERC-1155");
        } catch {
            revert("Not an ERC-1155 contract");
        }

        // Check balance
        uint256 balanceOfSeller = nft.balanceOf(msg.sender, _tokenId);
        require(balanceOfSeller >= _amount, "Insufficient balance for the specified amount");

        // Ensure approval: ERC-1155 requires isApprovedForAll to be true
        require(nft.isApprovedForAll(msg.sender, address(this)), 
            "Marketplace must be approved for all of your tokens on this contract"
        );

        // Generate a unique listing ID based on contract + tokenId
        bytes32 listingId = keccak256(abi.encodePacked(_nftContract, _tokenId));

        listings[listingId] = Listing({
            nftContract: _nftContract,
            tokenId: _tokenId,
            forSale: true,
            seller: msg.sender,
            amount: _amount,
            unitPrice: _unitPrice
        });

        emit NFTListed(msg.sender, _nftContract, _tokenId, _amount, _unitPrice);
    }

    function buyNFT(
        address _nftContract,
        uint256 _tokenId,
        uint256 _amount
    ) external payable nonReentrant {
        // Retrieve listing
        bytes32 listingId = keccak256(abi.encodePacked(_nftContract, _tokenId));
        Listing storage listing = listings[listingId];
        require(listing.forSale, "This item is not for sale");
        require(_amount > 0, "Amount must be greater than zero");

        IERC1155 nft = IERC1155(listing.nftContract);

        // Check if enough tokens are still available
        uint256 availableForSale = listing.amount;
        require(availableForSale >= _amount, "Not enough tokens available for sale");

        // Calculate total cost
        uint256 unitPrice = listing.unitPrice;
        uint256 totalCost = unitPrice * _amount;
        require(msg.value >= totalCost, "Insufficient ether sent for the amount requested");

        // Transfer NFTs from seller to buyer
        nft.safeTransferFrom(listing.seller, msg.sender, listing.tokenId, _amount, "");

        // Pay seller
        (bool success, ) = payable(listing.seller).call{value: totalCost}("");
        require(success, "Transfer failed");

        // Decrease available amount on listing
        if (availableForSale == _amount) {
            listing.forSale = false; // Sold out
        } else {
            listing.amount -= _amount;
        }

        emit NFTHarvested(msg.sender, listing.seller, listing.nftContract, listing.tokenId, _amount, totalCost);
    }

    function makeOffer(
        address _nftContract,
        uint256 _tokenId,
        uint256 _amount,
        uint256 _unitPrice
    ) external notSelf(msg.sender) nonReentrant {
        require(_amount > 0, "Amount must be greater than zero");
        require(_unitPrice > 0, "Unit price must be greater than zero");

        IERC1155 nft = IERC1155(_nftContract);
        
        // Check that the contract supports ERC-1155
        try nft.supportsInterface(0xd9b67a26) returns (bool supported) {
            require(supported, "Address does not implement ERC-1155");
        } catch {
            revert("Not an ERC-1155 contract");
        }

        // Check balance
        uint256 balanceOfMaker = nft.balanceOf(msg.sender, _tokenId);
        require(balanceOfMaker >= _amount, "Insufficient balance for the specified amount");

        // Ensure approval: ERC-1155 requires isApprovedForAll to be true
        require(nft.isApprovedForAll(msg.sender, address(this)), 
            "Marketplace must be approved for all of your tokens on this contract"
        );

        offers[_nftContract][_tokenId] = Offer({
            maker: msg.sender,
            nftContract: _nftContract,
            tokenId: _tokenId,
            amount: _amount,
            accepted: false
        });

        emit OfferMade(msg.sender, _nftContract, _tokenId, _amount, _unitPrice);
    }

    function acceptOffer(
        address _maker,
        address _nftContract,
        uint256 _tokenId
    ) external nonReentrant {
        Offer storage offer = offers[_nftContract][_tokenId];
        require(_maker == offer.maker, "Incorrect maker");
        require(!offer.accepted, "Offer already accepted");

        IERC1155MetadataURI nft = IERC1155MetadataURI(offer.nftContract);

        // Ensure the caller (seller) owns enough tokens
        uint256 balanceOfSeller = nft.balanceOf(msg.sender, _tokenId);
        require(balanceOfSeller >= offer.amount, "Insufficient seller's balance");

        // Ensure the seller has approved the marketplace for these tokens
        require(nft.isApprovedForAll(msg.sender, address(this)),
            "Seller must approve the marketplace to transfer these tokens"
        );

        // Get the URI and convert it to bytes to get its length
        string memory uri = nft.uri(_tokenId);
        uint256 totalCost = offer.amount * bytes(uri).length;
        require(address(this).balance >= totalCost, "Marketplace does not have enough funds");

        // Transfer NFTs from seller to buyer (maker)
        nft.safeTransferFrom(msg.sender, _maker, _tokenId, offer.amount, "");

        // Pay the maker
        (bool success, ) = payable(_maker).call{value: totalCost}("");
        require(success, "Transfer failed");

        offer.accepted = true;

        emit OfferAccepted(msg.sender, _maker, _nftContract, _tokenId, offer.amount, totalCost);
    }

    function withdraw() external onlyOwner nonReentrant {
    uint256 balance = address(this).balance;
    (bool success, ) = payable(owner()).call{value: balance}("");
    require(success, "Transfer failed");
}
}

@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @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.
 *
 * The initial owner is set to the address provided by the deployer. 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;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @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 {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling 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 {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _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);
    }
}

@openzeppelin/contracts/security/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

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 making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

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

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

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}

@openzeppelin/contracts/token/ERC1155/IERC1155.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC1155/IERC1155.sol)

pragma solidity >=0.6.2;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC-1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[ERC].
 */
interface IERC1155 is IERC165 {
    /**
     * @dev Emitted when `value` amount of tokens of type `id` are transferred from `from` to `to` by `operator`.
     */
    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);

    /**
     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256[] ids,
        uint256[] values
    );

    /**
     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `approved`.
     */
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);

    /**
     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
     *
     * If an {URI} event was emitted for `id`, the standard
     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
     * returned by {IERC1155MetadataURI-uri}.
     */
    event URI(string value, uint256 indexed id);

    /**
     * @dev Returns the value of tokens of token type `id` owned by `account`.
     */
    function balanceOf(address account, uint256 id) external view returns (uint256);

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(
        address[] calldata accounts,
        uint256[] calldata ids
    ) external view returns (uint256[] memory);

    /**
     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the zero address.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address account, address operator) external view returns (bool);

    /**
     * @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`.
     *
     * WARNING: This function can potentially allow a reentrancy attack when transferring tokens
     * to an untrusted contract, when invoking {IERC1155Receiver-onERC1155Received} on the receiver.
     * Ensure to follow the checks-effects-interactions pattern and consider employing
     * reentrancy guards when interacting with untrusted contracts.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
     * - `from` must have a balance of tokens of type `id` of at least `value` amount.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes calldata data) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * WARNING: This function can potentially allow a reentrancy attack when transferring tokens
     * to an untrusted contract, when invoking {IERC1155Receiver-onERC1155BatchReceived} on the receiver.
     * Ensure to follow the checks-effects-interactions pattern and consider employing
     * reentrancy guards when interacting with untrusted contracts.
     *
     * Emits either a {TransferSingle} or a {TransferBatch} event, depending on the length of the array arguments.
     *
     * Requirements:
     *
     * - `ids` and `values` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external;
}

@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC1155/extensions/IERC1155MetadataURI.sol)

pragma solidity >=0.6.2;

import {IERC1155} from "../IERC1155.sol";

/**
 * @dev Interface of the optional ERC1155MetadataExtension interface, as defined
 * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[ERC].
 */
interface IERC1155MetadataURI is IERC1155 {
    /**
     * @dev Returns the URI for token type `id`.
     *
     * If the `\{id\}` substring is present in the URI, it must be replaced by
     * clients with the actual token type ID.
     */
    function uri(uint256 id) external view returns (string memory);
}

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @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;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

@openzeppelin/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": false
  },
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.