Solidity – Passing Array of Structs to Contract with ABIEncoderV2 in Truffle

arrayssoliditystructtruffle

How do you pass an array of structs from Truffle (javascript) to a smart contract (Solidity)?

There are a few similar questions (like this one and this one) whose answers say you cannot pass a struct to a public function in solidity or are using a version of Solidity before 4.0.19. However, I'm using ABIEncoderV2, where this is not a problem.

I'm getting the following error:

Error: invalid solidity type!: tuple[]

Truffle test suite:

const foo = artifacts.require('./FOO.sol');
it('test', async () => {
    let coordsContract = await foo.new();
    const coord0 = {x: 100, y: 200};
    const coords = [coord0];
    const worked = await coordsContract.loopCoords(coords);
    assert.isTrue(worked);
});

Solidity contract:

pragma solidity ^0.4.23;
pragma experimental ABIEncoderV2;

contract FOO {
    struct Coordinates {
        uint256 x;
        uint256 y;
    }

    function loopCoords(Coordinates[] coords) public returns (bool) {
        for (uint i = 0; i < coords.length; i++) {
            //do stuff
        }
        return true;
    }
}

Best Answer

Problem is you are trying to pass javascript array coords to a solidity function loopCoords. Solidity function is not able to interpret coords as an array and it is interpreting it as a mapping.

I am not sure but I think your problem is how to pass an array as a parameter from javascript web3 to a solidity function You need to pass an argument of loopCoords as the following:

await coordsContract.loopCoords.getData(coords)
Related Topic