1

I want to create a modifier that accepts a dynamic array, like this:

modifier parameterizedTest(Set[] memory sets) {
    // ...
}

Where the Set struct is defined like this:

struct Set {
    uint256 x;
    uint256 y;
    uint256 expected;
}

Now, I know that normally one has to use multiple statements to define the array, like this:

Set[] memory sets = new Set[](1);
sets.push(Set(1,2,3));

But is there any way to "shortcut" that approach? Ideally, I would like to pass my arrays declaratively to the modifier, like this:

function testSomething() external parameterizedTest([Set(1,2,3)]) {
    // ...
}

I know that the code above does not compile. I wrote it just for demonstrational purposes.

Paul Razvan Berg
  • 17,902
  • 6
  • 73
  • 143

1 Answers1

1

Unfortunatelly, that syntax is not yet supported. It may be supported in the future.

Take a look at this code snippet:

//SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;

contract Counter {

uint256[] ints = [1,2,3]; // This syntax for value-type is supported

bytes[] bs = [bytes("")]; // Works

string[] strs = ["one", "two"]; // Works

// uint256[][] = [[1,2,3]]; // Does not work

// Set[] sets = [Set(1,2,3)]; // This syntax is not yet supported for structs because `Set(1,2,3)` is considered to be in memory and it cannot be assigned to storage like this

struct Set {
    uint256 x;
    uint256 y;
    uint256 expected;
}

modifier parameterizedTest(Set[] memory sets) {
    // ...
    _;
}

function testSomething(Set[] memory _sets) external parameterizedTest(_sets) {
    // ...
}

}

There's a shorthand way of declaring state arrays and assign values at the same time, but it does not work for arrays of structs since a statement like this Set(1,2,3) is considered to be in memory and it cannot be assigned from storage.

If your testSomething function receives the Set[] memory _sets, then you can certainly pass it to the modifier, as I showed in the example.

Jeremy Then
  • 4,599
  • 3
  • 5
  • 28
  • 1
    Thanks for your answer! Unfortunately, I cannot pass an array directly to testSomething, because I'm using Foundry. If I did that define an array as an argument, Foundry would fuzz the inputs, whereas I need to use pre-defined values. – Paul Razvan Berg Sep 05 '22 at 12:59