Solidity – How to Pass the Value in Bytes32[] Array
remixsolidity
Given this constructor:
function Voting(bytes32[] candidateNames) public {
candidateList = candidateNames;
}
How to pass pass the value in the parameter candidateNames when I deploy the contract in remix?
Best Answer
If you're willing to do a little text editing, here's a mostly painless way. Make new a contract (or temporarily add the function below to this contract and pass [] to the constructor when you run it). Hardcode the candidate names (note that I set the array size to 3 since I know it for this example):
function getBytes32ArrayForInput() pure public returns (bytes32[3] b32Arr) {
b32Arr = [bytes32("candidate1"), bytes32("c2"), bytes32("c3")];
}
Compile and run the function. You should get this output:
As the Solidity code specifies, you need to pass a bytes32 value as argument, not an ascii-encoded word. This is an hexadecimal-encoded value, so as a rule of thumb it should start with 0x.
Before passing your argument, you thus need to hex-encode it using for example one of web3 util's functions:
> web3.utils.fromAscii('tag1')
'0x74616731'
You can pass this hexadecimal value as an argument in the Remix console. Later when you call getTagsOfAdmin you'll simply need to apply the reverse transformation:
> web3.utils.toAscii('0x74616731')
'tag1'
Despite this added complexity, bytes32 prove a good alternative against strings because they have fixed length and hence require way less storage costs. Hope it helps!
PS: note that the above command-line examples use web3 v1.
Best Answer
If you're willing to do a little text editing, here's a mostly painless way. Make new a contract (or temporarily add the function below to this contract and pass
[]
to the constructor when you run it). Hardcode the candidate names (note that I set the array size to 3 since I know it for this example):Compile and run the function. You should get this output:
Then use a text editor to format it like this:
It's now in the proper format so that Remix will accept it in the constructor text field as
bytes32[]
.