solidity – How to Fix Exception When Calling a Function in a Library That Returns an Array in Solidity

exceptionshardhatsoliditysolidity-0.8.x

I have a solidity library that has a public function and it's returning a uint8[] array.

pragma solidity ^0.8.4;

library LibA {
    function getArray() public pure returns (uint8[] memory) {
        uint8[] memory arr;
        arr[0] = 100;
        ...

        return arr;
    }
}

Then I have a Solidity smart contract that references the library and calls the function trying to access the array defined in the library. The code looks like this.

pragma solidity ^0.8.4;

import "./LibA.sol";

contract SampleContract {

    function doSomething(uint8 _index) public pure returns (uint8) {
        return LibA.getArray()[_index];
    }
}

The code compiles just fine. I have a mocha unit test that is run using Hardhat to test the method and when I run the unit test I get the following exception.

Error: VM Exception while processing transaction: reverted with panic
code 0x32 (Array accessed at an out-of-bounds or negative index)

I am quite new to Solidity and I'm having trouble understanding exactly what is the reason for the exception and how to resolve it. Some help would be greatly appreciated.

Best Answer

I've never worked with libraries before, however I believe the issue might be that you are trying to have a dynamically sized array in memory. This should be

uint8[] memory arr = new uint8[](arraySize);

in order to allocate the space in memory beforehand.

Related Topic