3

I am going through a tutorial from 2017 that says it was updated in January of 2018. It says that currently you can not pass an array of strings directly to the constructor of a contract and that you have to use an array of something like byte32. Is that still the case?

If you can use an array of strings now and you have a link to an example page, then please share it.

3 Answers 3

9

You can actually use an array of byte32 as an argument to a solidity function as with this constructor function:

constructor(bytes32[] memory proposalNames) public {
    chairperson = msg.sender;
    voters[chairperson].weight = 1;

    // For each of the provided proposal names,
    // create a new proposal object and add it
    // to the end of the array.
    for (uint i = 0; i < proposalNames.length; i++) {
        // `Proposal({...})` creates a temporary
        // Proposal object and `proposals.push(...)`
        // appends it to the end of `proposals`.
        proposals.push(Proposal({
            name: proposalNames[i],
            voteCount: 0
        }));
    }
}

And this is how you can pass it using web3:

let args = ['one', 'two', 'three', 'four'];
ballot = await new web3.eth.Contract(JSON.parse(interface))
    .deploy({ 
        data: bytecode, 
        arguments: [args.map((arg) => web3.utils.asciiToHex(arg))]
    })
    .send({ from: accounts[0], gas: '6000000' });

The point is convert the string array to byte32 array (the hex representation), and just pass it along. The only thing I did to get the hex representation is this :

args.map((arg) => web3.utils.asciiToHex(arg))

If you have a byte32 return type in a solidity function, you can likewise use one of web3's utility function (web3.utils.bytesToHex('0xf2323de')) to convert it to a string value.

3
  • the constructor code is from the solidity docs: solidity.readthedocs.io/en/v0.5.0/solidity-by-example.html
    – mezi
    Commented Nov 18, 2018 at 8:39
  • Thanks. Have you had any problems with heavy gas usage with functions that accept an array of bytes 32 or "stack too deep" errors? Commented Nov 18, 2018 at 18:53
  • I had no problem with gas usage. For the above example I used 6000000 Wei for a gas, and it worked fine.
    – mezi
    Commented Nov 20, 2018 at 5:53
2

2022 here, yes it does now. Open this in Remix and use something like ["str1", "str2"] to deploy:

pragma solidity ^0.8.7;

contract Strings  {  
    string[] public stringParam;
   
    constructor(string[] memory _stringParam) {
        stringParam = _stringParam;
    }
}
1

Indeed, you cannot use an array of strings or bytes32. Question was already answered here ;).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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