0
votes

I want to add a struct to an array and get the first entry from a other function and its not working with web3, but If I add the struct to the array in the same function web3 is working and returns the entry as expected:

pragma solidity >=0.7.0;
pragma experimental ABIEncoderV2;

contract Payback {
    struct Address {
        uint256 id;
        string name;
        address _address;
    }

    Address[] addresses;

    function addAddress() external {
        Address memory newAddress = Address(
            1,
            "Test",
            0xDEE7796E89C82C36BAdd1375076f39D69FafE252
        );
        addresses.push(newAddress);
    }

    function getAddress() external view returns (Address memory) {
        return addresses[0];
    }
}

My Test is working:

it('gets Address', async () => {
    await paybackInstance.addAddress()
    let value = await paybackInstance.getAddress()
    assert.equal(value[0], "1")
    assert.equal(value[1], "Test")
    assert.equal(value[2], "0xDEE7796E89C82C36BAdd1375076f39D69FafE252")
  });

But if I want to return it with web3 I get an error: "VM Exception while processing transaction: invalid opcode"

let addresses = await contract.methods.getAddress().call()
    console.log(addresses)

I guess I do something wrong with storage/memory but not really understanding it because my test is passing...

1

1 Answers

0
votes

It looks like, with web3, you are not adding the struct to array and trying access value at index 0 which does not exist because the array's length is zero.