Solidity – Why Does a View Function Cost Gas?

ethers.jssolidity

I'm building an NFT marketplace. I have a view function that returns the NFTs of a user. However, this function requires a transaction and costs gas that the user must pay.

Here is the related part of the MarketContract code:

contract Market is ReentrancyGuard {
    using Counters for Counters.Counter;
    Counters.Counter private _listingCount;

    mapping(uint256 => Listing) public marketListings;

    struct Listing {
        uint256 listingId;
        address nftContractAdd;
        uint256 tokenId;
        address ownerAdd;
        uint256 price;
    }

    function getItemsOf (address wallet) public view returns (Listing[] memory) {
        uint resultCount = 0;
        for (uint i = 0; i < _listingCount.current(); i++) {
            if (marketListings[i].ownerAdd == address(wallet)) {
                resultCount++; 
            }
        }

        uint itemCount = 0;
        Listing[] memory items = new Listing[](resultCount);
        for (uint256 i = 0; i <= _listingCount.current(); i++) { 
            if(marketListings[i].ownerAdd == address(wallet)) {
                items[itemCount] = marketListings[i];
                itemCount++;
            }
        }

        return items;
    }
}

And, here is my frontend code:

async getListedItemsOfUser({ }, payload) {
        const { walletAddress } = payload

        const web3Modal = new Web3Modal();
        const connection = await web3Modal.connect();
        const provider = new ethers.providers.Web3Provider(connection);
        const signer = provider.getSigner();

        const marketContract = new ethers.Contract(
            Secrets.MARKET_CONTRACT_ADDRESS,
            MarketContract.abi,
            signer
        );

        try {
            const res = await marketContract.getListedItemsOf(walletAddress);
            console.log("listed items", res)
        } catch (err) {
            console.log(err)
        }
    }

Why does this function cost gas?

Here the ABI of all the contract code: GIST

Best Answer

You are calling getListedItemsOf method from your frontend. Shouldn't you be calling getItemsOf like you have posted in your question?

These two methdos have different stateMutability in the provided ABI.

Related Topic