Fede
Fede

Reputation: 1716

call revert exception when calling a view function with Panic code 50

I'm getting an error when calling a view function of my solidity contract from my frontend.

The error is listed in the docs as error 32:

0x32: If you access an array, bytesN or an array slice at an out-of-bounds or negative index (i.e. x[i] where i >= x.length or i < 0).

My contract:

address public owner;

struct FoodItem {
    address owner;
    string url;
    string name;
    string originCountry;
}

FoodItem[] public foodItems;

function addFoodItem(
    string memory url,
    string memory name,
    string memory originCountry
) public {
    foodItems.push(FoodItem(msg.sender, name, url, originCountry));
}

function getFoodItemsByOwner() public view returns (FoodItem[] memory) {
    uint256 itemCount = 0;

    for (uint256 i = 0; i < foodItems.length; i++) {
        if (foodItems[i].owner == msg.sender) {
            itemCount += 1;
        }
    }

    FoodItem[] memory myfoods = new FoodItem[](itemCount);
    for (uint256 i = 0; i < foodItems.length; i++) {
        if (foodItems[i].owner == msg.sender) {
            myfoods[i] = foodItems[i];
        }
    }

    return myfoods;
}

And my function from react:

    const getDishesByUser = async () => {
    const { ethereum } = window;
    if(ethereum) {
        const provider = new ethers.providers.Web3Provider(ethereum);    
        const signer = provider.getSigner();
        const contract = new ethers.Contract(abiFoodAddress, Food.abi, signer);
        const data = await contract.getFoodItemsByOwner();
       console.log(data);
        setDishesByuser(data)
        //router.push('/');
    }

  };

  useEffect(() => {
    getDishesByUser();
  }, []);

Complete error output in the console:

index.js?dd68:224 Uncaught (in promise) Error: call revert exception; VM Exception while processing transaction: reverted with panic code 50 [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ] (method="getFoodItemsByOwner()", data="0x4e487b710000000000000000000000000000000000000000000000000000000000000032", errorArgs=[{"type":"BigNumber","hex":"0x32"}], errorName="Panic", errorSignature="Panic(uint256)", reason=null, code=CALL_EXCEPTION, version=abi/5.7.0)

Upvotes: 2

Views: 1185

Answers (1)

CHINONSO
CHINONSO

Reputation: 1

You can console log foodItems in addFoodItem function to be sure that you actually pushed the items. If not, you may try:

Mapping(address => FoodItem[]) public  foodItems;

So you can do:

foodItems[owner].push(FoodItem(msg.sender, name, url, originCountry));

But you have to specify who the owner is

Upvotes: 0

Related Questions