[Ethereum] How to convert string to bytes32 properly

bytes32solidityweb3js

In my solidity I'm using a mapping like this:

mapping(bytes32 => uint) items;

constructor() {
   items["test"] = 2;
}   

function getItem(bytes32 key) returns(uint) {
   return items[key];
}

My question is now how to call the function in JS using web3 1.0? I have to convert the string to hex. Using web3.utils.stringToHex("test") gives me 0x74657374. Using that I'm getting invalid bytes32 value. The function web3.utils.asciiToHex returns 0x7465737400000000000000000000000000000000000000000000000000000000 which looks for me like a different value. The function call succeeds but I don't get the expected result value of 2.
I also tried web3Utils.padLeft(web3Utils.stringToHex(params[index]), 64); which gives 0x0000000000000000000000000000000000000000000000000000000074657374. Function call succeeded but result value is also 0 not 2.

Best Answer

If you're on web3 v0.x, then:

  • Use web3.fromAscii before you send the string to the smart contract
  • Use web3.toAscii after you read the string from the smart contract

If you're on web3 v1.x, then: