5
public String solFunction(String str) {
    byte[] byteValue = DatatypeConverter.parseHexBinary(str);
    Bytes32 strInBytes = new Bytes32(byteValue);
    try {
        Uint256 value = contract.showPoint(strInBytes).get();
        return value.getValue().toString();
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
    return null;
}

// web3j generated java code for solidity program
public Future<Uint256> showPoint(Bytes32 byteValue) {
        Function function = new Function("showPoint", 
                Arrays.<Type>asList(rewardType), 
                Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));
        return executeCallSingleValueReturnAsync(function);
    }

I am trying to send Bytes32 type argument to SmartContract function using web3j. It always throws exception

Input byte array must be in range 0 < M <= 32 and length must match type

I have already checked Numeric datatype converter of web3j and this solutions. issue reported in git web3j

This is my solidity program

contract MyContract {
    address public owner; // Store owner address
    mapping (address => mapping (bytes32 => uint)) value;

    function MyContract (uint initValue, bytes32 chkByte) {
        owner = msg.sender;
        reward[msg.sender][chkByte] = initValue;
    }

    function showAvailReward(bytes32 chkByte) constant returns(uint) {
            return value[msg.sender][chkByte];
        }
}
6

SOLVED!!! LONG/Detailed METHOD!!! (Shorter Version at bottom)

The main problem was Bytes32(byte[]) only supports 32 length byte[]. Also keep in mind Numeric.hexStringToByteArray(strValueInHex) converts any HexString to byte[].

This is the process:

String => Hex => 32 length Hex (ie. 64 length HexString) => byte[] => Bytes32

Note: "00" = 1 Hex length & 2 String length

Here is How I achieved String to Bytes:

String to 64 length HexString:

// String to 64 length HexString (equivalent to 32 Hex lenght)
public static String asciiToHex(String asciiValue)
{
    char[] chars = asciiValue.toCharArray();
    StringBuffer hex = new StringBuffer();
    for (int i = 0; i < chars.length; i++)
    {
        hex.append(Integer.toHexString((int) chars[i]));
    }

    return hex.toString() + "".join("", Collections.nCopies(32 - (hex.length()/2), "00"));
}

64 length HexString to 32 length byte[]:

byte[] myStringInByte = Numeric.hexStringToByteArray(asciiToHex("myString"));

32 length byte[] to Bytes32:

Bytes32 myStringInBytes32 = new Bytes32(myStringInByte);

Now myStringInBytes32 is accepted as by web3j's contract function. In my case corrected solFunction(String str) is:

public String solFunction(String str) {
    String strInHex = asciiToHex(str);
    Bytes32 strInBytes32 = new Bytes32(Numeric.hexStringToByteArray(strInHex));
    try {
        Uint256 value = contract.showPoint(strInBytes32).get();
        return value.getValue().toString();
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
    return null;
}

If your solidity function returns data in Bytes32 then Here is how to get value from returned Bytes32 data.

String dataInString = hexToASCII(Numeric.toHexStringNoPrefix(dataInBytes32);

Function hexToASCII

public static String hexToASCII(String hexValue)
    {
        StringBuilder output = new StringBuilder("");
        for (int i = 0; i < hexValue.length(); i += 2)
        {
            String str = hexValue.substring(i, i + 2);
            output.append((char) Integer.parseInt(str, 16));
        }
        return output.toString();
    }

String-to-Hex & Hex-to-String Help From Here


SHORT/SIMPLIFIED Method:

String to Bytes32:

public static Bytes32 stringToBytes32(String string) {
        byte[] byteValue = string.getBytes();
        byte[] byteValueLen32 = new byte[32];
        System.arraycopy(byteValue, 0, byteValueLen32, 0, byteValue.length);
        return new Bytes32(byteValueLen32);
    }

Bytes32 to String:

StringUtils.newStringUsAscii(varTypeBytes32.getValue());

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.