Skip to content

Instantly share code, notes, and snippets.

@EbenezerGH
Last active November 26, 2018 20:21
Show Gist options
  • Save EbenezerGH/3e995ac6fd62c09d6e2deab8742d84ca to your computer and use it in GitHub Desktop.
Save EbenezerGH/3e995ac6fd62c09d6e2deab8742d84ca to your computer and use it in GitHub Desktop.
byte array must be in range 0 < M <= 32

byte array must be in range 0 < M <= 32

You can simply convert a string to a bytes32 format in kotlin or solidity

Solidity:
    function stringToBytes32(string memory source) private pure returns (bytes32 result) {
        bytes memory tempEmptyStringTest = bytes(source);
        if (tempEmptyStringTest.length == 0) {
            return 0x0;
        }
        assembly {
        result := mload(add(source, 32))
        }
    }
Kotlin:
    fun stringToBytes32(string: String): Bytes32 {
        val byteValue = string.toByteArray()
        val byteValueLen32 = ByteArray(32)
        System.arraycopy(byteValue, 0, byteValueLen32, 0, byteValue.size)
        return Bytes32(byteValueLen32)
    }

classes where error is thrown in web3j

package org.web3j.abi.datatypes;

/**
 * Statically allocated sequence of bytes.
 */
public class Bytes extends BytesType {

    public static final String TYPE_NAME = "bytes";

    protected Bytes(int byteSize, byte[] value) {
        super(value, TYPE_NAME + value.length);
        if (!isValid(byteSize, value)) {
            throw new UnsupportedOperationException(
                    "Input byte array must be in range 0 < M <= 32 and length must match type");
        }
    }

    private boolean isValid(int byteSize, byte[] value) {
        int length = value.length;
        return length > 0 && length <= 32 && length == byteSize;
    }
}
package org.web3j.abi.datatypes.generated;

import org.web3j.abi.datatypes.Bytes;

/**
 * Auto generated code.
 * <p><strong>Do not modifiy!</strong>
 * <p>Please use org.web3j.codegen.AbiTypesGenerator in the 
 * <a href="https://github.com/web3j/web3j/tree/master/codegen">codegen module</a> to update.
 */
public class Bytes32 extends Bytes {
    public static final Bytes32 DEFAULT = new Bytes32(new byte[32]);

    public Bytes32(byte[] value) {
        super(32, value);
    }
}

Another solution is to debug through these 2 specific classes and see the size of the byte[] that's being passed. After finding the descrepency you can alter the datasize enough to avoid the exception that's passed when trying to use these web3js libraries.

For creating a simple 32x hash to convert your string -> ByteArray you can use http://www.md5hasher.net/. This can be used as a final layer of encryption to your message before sending it to the contract.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment