[SOLVED] Fetching Market Items from NFT Marketplace Contract

Hi, I am developing an NFT marketplace. I have a contract that has a function I can call to fetch the items that are on sale:

    function fetchMarketItems() public view returns (MarketItem[] memory) {
        uint itemCount = _itemIds.current();
        uint unListedItemCount = _itemIds.current() - _itemsNotListed.current();
        uint currentIndex = 0;

        MarketItem[] memory items = new MarketItem[](unListedItemCount);
        for (uint i = 0; i < itemCount; i++) {
            if (idToMarketItem[i + 1].owner == address(this) && idToMarketItem[i + 1].status == ListingStatus.Active) {
                uint currentId = i + 1;
                MarketItem storage currentItem = idToMarketItem[currentId];
                items[currentIndex] = currentItem;
                currentIndex += 1;
        return items;

Also the contract has an event to be fired when a new item is listed like below:

     event MarketItemCreated (
        uint indexed itemId,
        address indexed nftContract,
        uint256 indexed tokenId,
        address seller,
        address owner,
        uint256 price,
        ListingStatus status

So I have two options to fetch the market data:

  1. Call the fetchMarketItems() function -> fetch the data -> parse/format the data and use on the frontend.
  2. Watch the smart contract event using Stream API -> Save to my Database when an event is fired -> Fetch the data from the database with appropriate filters-> Display on the frontend

My question is:
Considering I have implemented some other functions in the contract to fetch different types of items like onsale items, items with cancelled listing or sold, items of a specific seller etc.

  • Which method would be better in terms of performance, reliability etc.
  • Is it a good practice to fetch data from contracts?

It is perfectly fine to fetch data from contracts especially when it needs to be realtime/accurate. If the data isn’t going to change much it may be better to cache or store it in a database instead of constantly querying the blockchain. In this case since it will need to be reliable you should look at calling your contract for the data at least as a backup.

Also consider how to handle any failures e.g. if your backend went down.

1 Like

Thanks, appreciate it.

@alex do you have an example of when storing in a database would be a better option in a web3 context? for example, I want to build a marketplace similar to opensea where I want to show users such data as current price, offers made, and item activity. there will be up to 3000 new NFTs per week.
what would you suggest in this case? thanks

Something like metadata or token_uri which likely won’t change often. OpenSea for example is probably not constantly querying the chain for every visit to an NFT page - this is also where they have a refresh metadata option.

It is up to you which approach to take.

1 Like