Ich habe eine API zum Hinzufügen von Kandidaten erstellt. Aber wenn ich die API starte, bekomme ich einen Fehler:
Input byte array must be in range 0 < M <= 32 and length must match type
Mein Codeschnipsel für addCandidates lautet:
@RequestMapping("/addCandidate")
public String addCandidateDetails(@RequestParam("candidateName") String candidateName, @RequestParam("elecName") String elecName) {
try{
String contractAddress = contract.getContractAddress();
System.out.println(contractAddress);
contract.addCandidate(candidateName.getBytes(), elecName.getBytes());
}
catch (Exception e) {
String error = e.getMessage();
return error;
}
return "Success";
}
Der Code für den Vertrag in Java lautet:
public RemoteCall<TransactionReceipt> addCandidate(byte[] candidateName, byte[] election) {
final Function function = new Function(
FUNC_ADDCANDIDATE,
Arrays.<Type>asList(new org.web3j.abi.datatypes.generated.Bytes32(candidateName),
new org.web3j.abi.datatypes.generated.Bytes32(election)),
Collections.<TypeReference<?>>emptyList());
return executeRemoteCallTransaction(function);
}
Kann mir einer sagen was ich hier falsch mache?? Ist getBytes() der richtige Weg, um String in Bytearray zu konvertieren? Alle Hinweise wären willkommen. Danke schön!!
Ich habe die Lösung gefunden: Ich habe die folgende Funktion in meinem Soliditätsvertrag implementiert:
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))
}
}
Benutzte es in Funktion:
function addCandidate(string candidateName, string election) public {
bytes32 c1 = stringToBytes32(candidateName);
bytes32 e1 = stringToBytes32(election);
candidates[c1] = candidate(c1,e1,0);
}
Ismael