Search code examples
ethereumsolidity

Is there a way to return an array of structs in Solidity without de-structuring the fields?


I've been doing some research around this issue, but I couldn't find a definite answer. I'm using solidity 0.4.24.

I have a contract like this:

contract {
    struct FutureOperation is Ownable {
        uint256 date;
        uint256 price;
        uint256 amount;
        string name;
    }

    FutureOperation[] futureOperations;

    // ...

    function getAllFutureOperations() public onlyOwner returns (FutureOperation[]) {
        return futureOperations;
    }
}

When I compile this in Remix I get the following error:

browser/myfuturetoken.sol:53:64: TypeError: This type is only supported in the new experimental ABI encoder. Use "pragma experimental ABIEncoderV2;" to enable the feature.

I found some blog posts saying that I should de-structure the fields in the struct to return them as arrays of the primitive types. So, in this case, it would look something like this:

function getAllFutureOperations() public onlyOwner returns (uint256[] dates, uint256[] prices, uint256[] amounts, string[] names) {
        return futureOperations;
    }

Is there an alternative for that? Are the newer compilers capable of returning an array of structs?

Thanks.


Solution

  • As error stated, returning dynamic array is not supported by compiler yet. However, experiment feature supported it. To use experimental compiler, you need to make some changes as follows,

    pragma experimental ABIEncoderV2;
    
    contract myContract{
    
        struct FutureOperation {
            uint256 date;
            uint256 price;
            uint256 amount;
            string name;
        }
    
        string[] futureOperations;
    
        function getAllFutureOperations() public view returns (string[] memory) {
            return futureOperations;
        }
    
    } 
    

    Note: make sure to not use experimental things in production version