solidity truffle bytes32 – Problem with bytes32 values

bytes32soliditytruffle

I am facing problem with bytes32.

Here is my sample contract:

pragma solidity ^0.4.16;

  contract Test {

    bytes32 public input;
    function test(bytes32 _in) public {
    input = _in;
  }
}

The problem is in truffle dev, no matter how I run the test function, the input value is the same. For example, if I run:

MyContract.deployed().then(inst => { inst.test(12, {from: >web3.eth.accounts[0]}) });

Then I get the result:

truffle(develop)> MyContract.deployed().then(inst => { return >inst.input.call() });
'0xc000000000000000000000000000000000000000000000000000000000000000'

Also, if I run:

MyContract.deployed().then(inst => { inst.test("12", {from:
web3.eth.accounts[0]}) });

The result is the same:

MyContract.deployed().then(inst => { return inst.input.call() });
'0xc000000000000000000000000000000000000000000000000000000000000000'

I don't think it's normal..
Any ideas what I might be doing wrong?

Thanks

Best Answer

Bytes are represents as hex value. In your case 0xc of base10 is 12.

In web3js, based on ABI method it will convert value into its corresponding datatype and transmit data to network. Some times in javascript big integers/hex values are represents as a string. Before sending to actual network, web3js will convert to eq values.

That means "12" of string is converted into integer and converted into hex value.

"12" of string type but its numeric type(because it contains only 0-9 values) so web3js will convert into integer type converted into 12. 12 Hex representation is 0xc. But you mention its bytes32. It will pad 32 bit. So final hex string would be 0xc000000000000000000000000000000000000000000000000000000000000000

Use web3.utils.fromAscii(string) will convert into string bytes(hex string) [1 eq:0x31 and 2 eq: 0x32]

Try to change below line for string

  MyContract.deployed().then(inst => {        
     inst.test(web3.fromAscii("123"), {from:web3.eth.accounts[0]}) 
  });

Your output would be bytes32 [Because 32byte padding] 0x3132000000000000000000000000000000000000000000000000000000000000

Get value as a string:

  MyContract.deployed().then(inst => {        
     web3.toAscii(inst.input())
  });
Related Topic