1

I have a public array of structs. Each struct has a fixed-length array inside of it. How do I go about accessing a specific struct's array member via web3? The contract is compiling, but when I use the public array's getter function, it leaves the array member out.

Solidity:

pragma solidity ^0.4.21;

contract Foo {
    struct Bar {
        bytes32 a;
        uint8[9] b;
    }

    Bar[] public bars;

    function add(bytes32 _a, uint8[9] _b) public {
        bars.push(Bar(_a, _b));
    }
}

web3:

let foo = await Foo.new();
await foo.add("banana", [1, 1, 2, 3, 5]);
let bar = await foo.bars(0);
assert.equal(foo[0], "banana");
assert.equal(foo[1], [1, 1, 2, 3, 5]); // fails, returns undefined
2

One way to solve this is to create a custom getter function to expose the array within the struct.

Solidity:

pragma solidity ^0.4.21;

contract Foo {
    struct Bar {
        bytes32 a;
        uint8[9] b;
    }

    Bar[] public bars;

    function add(bytes32 _a, uint8[9] _b) public {
        bars.push(Bar(_a, _b));
    }

    function getBarBs(uint256 _index) public returns (uint8[9]) {
        return bars[_index].b;
    }
}

web3:

let bs = await foo.getBarBs(0);
assert.equal(bs, [1, 1, 2, 3, 5]); // succeeds!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.