I have created an api to addCandidates. But when i run the api i get error:

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

My codesnippet for addCandidates is:

    public String addCandidateDetails(@RequestParam("candidateName") String candidateName, @RequestParam("elecName") String elecName) {

        String contractAddress = contract.getContractAddress();
        contract.addCandidate(candidateName.getBytes(), elecName.getBytes());
        catch (Exception e) {
            String error = e.getMessage();
            return error;
        return "Success";

Code for contract in java is:

public RemoteCall<TransactionReceipt> addCandidate(byte[] candidateName, byte[] election) {
    final Function function = new Function(
            Arrays.<Type>asList(new org.web3j.abi.datatypes.generated.Bytes32(candidateName), 
            new org.web3j.abi.datatypes.generated.Bytes32(election)), 
    return executeRemoteCallTransaction(function);

Can any one tell me what I am doing wrong here?? Is getBytes() the right way to convert string to bytearray?? Any leads would be appreciated. Thank you!!


I found the solution: I implemented the following function in my solidity contract:

function stringToBytes32(string memory source) public returns (bytes32 result) {
    bytes memory tempEmptyStringTest = bytes(source);
    if (tempEmptyStringTest.length == 0) {
        return 0x0;

    assembly {
        result := mload(add(source, 32))

Used it in function:

  function addCandidate(string candidateName, string election) public {
    bytes32 c1 = stringToBytes32(candidateName);
    bytes32 e1 = stringToBytes32(election);

      candidates[c1] = candidate(c1,e1,0);

  • That solution will trunc strings larger than 32 bytes, also it might have problems with strings shorter than 31 bytes if they are compressed. – Ismael Sep 28 '18 at 13:31

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.