I have the following Solidity function:
function func(bytes32[2] data) external {
bytes32 x;
bytes32 y;
x = data[0];
y = data[1];
}
I'm trying to call it from Javascript (using web3), but passing an array a parameter doesn't work. I tried the following methods:
var arr = ["field1", "field2"];
contracts['MyContract'].contract.func(arr);
or:
contracts['MyContract'].contract.func(["field1", "field2"]);
or:
contracts['MyContract'].contract.func("field1", "field2");
None of those methods work.
Is there a way to pass an array as a parameter from Javascript to a Solidity function?
Best Answer
Here's what works for me using getData to populate a transaction data: field
The contract is an array getter setter:
The gotcha is that if you are changing state your array needs to be in storage and modified with a transaction...
This is a verbose ( includes gas estimation) but hopefully clear way to set it in web3, I am using Node.js and Parity:
And getting the Array value:
You could also just call a contract's function with parameters, but the function needs to be pure, which is not enforced yet( i.e. your compiler might not compile the contract).
and calling it :
The above works with compilers 0.4.17 and above (just update solc) , below you are back to calling it with a transaction that costs gas...
Check both in remix the one on top doesn't incur in gas, while the one in the bottom does.