I am getting error - Element type must be nullable if array is holey while running the contract

608 Views Asked by At

{ "error": "wasm execution failed with error: FunctionCallError(HostError(GuestPanic { panic_msg: "Element type must be nullable if array is holey, filename: \"~lib/array.ts\" line: 103 col: 40" }))", "logs": [], "block_height": 82571830, "block_hash": "2grrzf57dPYQfnyUJZB7jw2zdqe7XsxBZBAdoSZ5wNMa" }

Code

for(let i:i32 =0 ; i < reviews.length ; i++)
{
   let condition = reviews[i].restaurant.restaurant_name==restaurantName;
   if(condition)
   {
      reviews_[i] = reviews[i].review;

   }
    
}

return reviews_;

}

1

There are 1 best solutions below

1
On BEST ANSWER

I think this function will create "holes" in the array because of the condition in your for loop. Instead of using the same length for reviews_ and reviews, you could create an empty reviews_ array, and push elements to it instead (see example, getShortList, below)

Having a holey list will look something like this

[review1, , , , review5, review6, , review8];

Instead of having unknown elements, you either have to fill the blanks with a null-able elements, e.g. an empty review

[review1, emptyReview, emptyReview, emptyReview, review5, review6, emptyReview, review8];

Or just make sure the list only contains elements without any "holes" in the array (a "packed" array)

[review1, review5, review6, review8];

Consider the following example

// Will panic at runtime due to holes in the list
getListWithHoles(): string[] {
  const arr = new Array<string>(5);
  for (let i = 0; i < arr.length; ++i) {
    if (i > 2) {
      arr[i] = "";
    }
  }
  return arr; // will return [,,,"",""];
}

// Here's how we can fix it. Return a "packed" array
getShortList(): string[] {
  const arr: string[] = [];
  for (let i = 0; i < 5; ++i) {
    if (i > 2) {
      arr.push("");
    }
  }
  return arr; // will return ["",""];
}