0

I need to pass array as argument to contract constructor using truffle deployment script.

My contract code looks like this:

pragma solidity ^0.5.0;

contract ArrayArgument {
    uint[] public arrsv;

    constructor(uint[] memory arr) public {
        for(uint i=0; i< arr.length; i++)
        {
            arrsv[i] = arr[i];
        }
    }

    function fetcharrayindexvalue(uint index) public view returns (uint)
    {
        return arrsv[index];
    }
}

My deployment script looks like this:

var ArrayArgument = artifacts.require("ArrayArgument");

module.exports = function (deployer) {
    deployer.deploy(ArrayArgument, [10, 12, 35]);
};  

But when I try to migrate my contract, I get the following error:

Error:  *** Deployment Failed ***

"ArrayArgument" hit an invalid opcode while deploying. Try:
   * Verifying that your constructor params satisfy all assert conditions.
   * Verifying your constructor code doesn't access an array out of bounds.
   * Adding reason strings to your assert statements.

  at C:\Users\Saurab Marjara\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-deployer\src\deployment.js:364:1
  at <anonymous>
  at process._tickCallback (internal/process/next_tick.js:188:7)
Truffle v5.0.8 (core: 5.0.8)
Node v8.10.0

How do I pass an array argument to a contract constructor from the deployment script ?

0

The "ArrayArgument" hit an invalid opcode while deploying error is due to a problem which occurs during runtime (i.e., not because of how you pass the array to the constructor).

The problem is that the initial length of the dynamic array uint[] public arrsv is 0.

So you cannot access (neither read nor write) elements in this array via arrsv[i].


Change this:

arrsv[i] = arr[i];

To this:

arrsv.push(arr[i]);
3
  • thank you so much. I was really at my wit's end regarding this..... again thank you. – saurab marjara Feb 8 '20 at 8:51
  • @saurabmarjara: You're welcome. What does wit's end mean? – goodvibration Feb 8 '20 at 8:52
  • :) wit's end means not knowing what to do next – saurab marjara Feb 9 '20 at 6:32

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.