Search code examples
blockchainsoliditysmartcontractstruffle

Solidity - Check if an index exists in contract A from Contract B


I have two contracts called A and B. I defined an array variable in contract A. I want to check if an index exists or not from contract B.

A.sol

contract A {
    SomeStruct[] private myArray;
    /// @notice Check if an index exists
    function isIndexExists(uint256 index) public view returns (bool) {
      if (myArray[index].isExist) {
        return true;
      } else {
        return false;
      }
    }
}

B.sol

contract B is A {
  function todo(uint256 index) public view returns (bool) {
    if (isIndexExists(index)) {
      // ... logic
    } else {
      revert("Index in not exist")l
    }
  }
}

The isIndexExists function works well When called directly from contract A, But in B an error occurs.

I make this call from the JS test environment in Truffle.

Error: Error: Returned error: VM Exception while processing transaction: revert


Solution

  • Array myArray is dynamically sized. You cannot safely try to access an element with an arbitrary index using the [] operator, you first need to check if the index is out of bounds. Here is how you could change your function in contract A to achieve this:

    function isIndexExists(uint256 index) public view returns (bool) {
      // If the index is out of bounds, then there is no such element
      if (index >= myArray.length) {
        return false;
      }
      
      // We know that there is an object with that index, so check its 'isExist' property
      return myArray[index].isExist;
    }
    

    BTW, note that when you are checking some expression that returns a boolean, you can directly return that value. You don't need the redundant if-else, which takes 5 lines compared to this approach which only takes one line of code.