3

The output of hash function SHA256 is a hex string of size 64. For example: 3ed54831f488a22b28398de0c567a3b064b937f54f81739ae9bd545967f3abab

I want to call the function of a smart contract with the following structure:

function register(bytes32 hash)

and pass the hex as an argument.

I use the web3 JavaScript library.

First I tried to pass the argument without any conversion. The result was a truncation of the last 32 bytes

Then I tried web3's fromAscii function with the same results.

I also tried hexToBytes and bytesToHex functions from the 1.x version. hexToBytes returns a byte array of size 32. When I pass the array to the smart contract function the results are totally different from the expected ones.

So how do I convert a hex of 32 bytes (64 character hex) in a format suitable for a bytes32 function argument ?

I know I can use bytes or string instead of bytes32 but I would rather avoid it as the hex of SHA256 is indeed 32 bytes.

EDIT

I create a test contract and test it in remix. I call set function with input 0x3fd54831f488a22b28398de0c567a3b064b937f54f81739ae9bd545967f3abab. The value is not truncated and I get the expected results.

pragma solidity ^0.4.24;

contract Test {
    bytes32 public hash;

    function set(bytes32 h) public {
        hash = h;
    }
}

So, the problem should be in the web3 library or JS itself right ?

UPDATE

I use the truffle-contract library to call my smart contract's functions

  • 1
    Total guess, but did you try prefixing the 'hex' string with '0x'? – Thomas Jay Rush Jul 6 '18 at 14:18
  • Yes, I did for all cases. Same results. – Laxmana Jul 6 '18 at 14:38
  • I know it is not answer to your question, but if you are at the beginning of your project I suggest you to use ethers.js - github.com/ethers-io/ethers.js Truffle contract and web3 really often has strange and unexpected behaviors. – Kristian Jul 6 '18 at 15:17
2

Pass it as a string "0x3fd54831f488a22b28398de0c567a3b064b937f54f81739ae9bd545967f3abab" It won't get truncated.

If this not solve read this: passing String object with "0x.." value as bytes32 to a solidity function

  • Thanks. Very useful links. Passing as a string with prefix "0x" is not working. I tried the other methods but I am getting a out of gas exception. – Laxmana Jul 13 '18 at 11:15
  • Check all intermediate inputs and outputs on the console log, the error must be somewhere else – user38075 Jul 14 '18 at 11:37
  • I was converting the input to bytes before passing it as: web3.fromAscii(value). Removing the conversion and pass the input as 0x... worked. – Laxmana Jul 23 '18 at 10:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.