2

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.

5

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.

|improve this answer|||||
1

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

|improve this answer|||||

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.