com.cryptape.cita.utils.TypedAbi Maven / Gradle / Ivy
package com.cryptape.cita.utils;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import com.cryptape.cita.abi.TypeReference;
import com.cryptape.cita.abi.datatypes.Address;
import com.cryptape.cita.abi.datatypes.Bool;
import com.cryptape.cita.abi.datatypes.DynamicArray;
import com.cryptape.cita.abi.datatypes.DynamicBytes;
import com.cryptape.cita.abi.datatypes.StaticArray;
import com.cryptape.cita.abi.datatypes.Type;
import com.cryptape.cita.abi.datatypes.Utf8String;
import com.cryptape.cita.abi.datatypes.generated.AbiTypes;
public class TypedAbi {
public static class InvalidAbiType extends Exception {
private String invalidTypeName;
public InvalidAbiType(String name) {
this.invalidTypeName = name;
}
@Override
public String toString() {
return "Invalid ABI type: " + invalidTypeName;
}
}
public static class ArgRetType {
// rawType is DynamicArray.class or StaticArrayX.class
private Class rawType;
private Class baseType;
public ArgRetType(Class rawType, Class baseType) {
this.rawType = rawType;
this.baseType = baseType;
}
public ArgRetType(Class baseType) {
this.rawType = null;
this.baseType = baseType;
}
public static ArgRetType newDynamicArray(Class baseType) {
return new ArgRetType(DynamicArray.class, baseType);
}
public static ArgRetType newStaticArray(String length, Class baseType) {
Class staticArray;
try {
staticArray = Class.forName(
"com.cryptape.cita.abi.datatypes.generated.StaticArray" + length);
} catch (ClassNotFoundException e) {
staticArray = StaticArray.class;
}
return new ArgRetType(staticArray, baseType);
}
public Type javaToAbi(Object value) throws Exception {
if (this.rawType != null) {
// NOTE: only support Array and List
Constructor arrayCtor = this.rawType.getDeclaredConstructor(List.class);
List list = new ArrayList<>();
if (value.getClass().isArray()) {
Object[] args = (Object[]) value;
for (Object arg : args) {
list.add(fromSingleJavaValue(arg));
}
} else {
List