Solidity – How to Pass Parameters to Remix

remixsolidity

I am trying to implement the contract below in REMIX.

If I try to pass parameters to appendTags as "tag1", I get an error as Error:

invalid bytes32 value (arg="", type="string", value="tag1")

How can I pass parameters to the function appendTags in REMIX ?

contract Post{

struct tags{
bytes32[] tagged; 
}

mapping(address => tags) adminTags;

function appendTags(address addrs, bytes32 tag) public { 
 adminTags[addrs].tagged.push(tag); 
} 

function getTagsofAdmin(address addrs) public view returns(bytes32[]){ 
return adminTags[addrs].tagged; 
}

}

Best Answer

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.

Related Topic