0

This is my contract

pragma solidity ^0.4.20;

contract Test {
    struct TestStruct {
        bytes32 name;
        mapping(uint => address) tesMapping;
    }

    TestStruct[] public testStructs;

    function Test(bytes32[] names) {
        for (uint i = 0; i < names.length; i++) {
            testStructs[i] = TestStruct(names[i]);
        }
    }
}

I'm using web3 v1.0. I create a new contract instance with:

c = new web3.eth.Contract(abi, from, { 
    data: data
});

where abi, from and data are defined in the right way previously.

When I try to estimate the gas needed for deploy in this way:

c.deploy({ 
    data: data, 
    arguments: myArgs
}).estimateGas(console.log);

I get this error:

Error: Returned error: VM Exception while processing transaction: invalid opcode

If I delete the body of the constructor (I leave the constructor empty), I get null.

Is there something wrong in the for loop in the constructor?

0

You're writing past the end of your array.

TestStruct[] public testStructs;

function Test(bytes32[] names) {
    for (uint i = 0; i < names.length; i++) {
        testStructs[i] = TestStruct(names[i]);
    }
}

testStructs is a dynamically-sized array with an initial size of 0. The first iteration of the loop, you attempt to write to testStructs[0], which is out of bounds.

Use push instead:

TestStruct[] public testStructs;

function Test(bytes32[] names) {
    for (uint i = 0; i < names.length; i++) {
        testStructs.push(TestStruct(names[i]));
    }
}

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.