org.web3j.utils.Strings Java Examples

The following examples show how to use org.web3j.utils.Strings. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RunnerTest.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void generateJavaCode() {
	String binPath = RunnerTest.class.getClassLoader().getResource(bin).getPath();
	String abiPath = RunnerTest.class.getClassLoader().getResource(abi).getPath();

	String outputPath = tempDirPath;
	// String outputPath = System.getProperty("user.dir").replace("console", "core") + "/src/test/java/";
	String packageName = "com.platon.sdk.contracts";

	String[] params = { "solidity", "generate", binPath, abiPath, "-o", outputPath, "-p", packageName };
	try {
		Runner.main(params);
	} catch (Exception e) {
		logger.error("Failed to generate Java code: " + e.getMessage(), e);
	}

	String sourceFile = tempDirPath + File.separator + packageName.replace('.', File.separatorChar) + File.separator
			+ Strings.capitaliseFirstLetter("HumanStandardToken") + ".java";

	boolean condition = new File(sourceFile).exists();

	Assert.assertTrue("Java wrapper source code generator for Solidity ABI format error.", condition);
}
 
Example #2
Source File: TruffleJsonFunctionWrapperGeneratorTest.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
private void testCodeGeneration(
        String contractName, String inputFileName, String packageName, String types)
        throws Exception {

    TruffleJsonFunctionWrapperGenerator.main(Arrays.asList(
            types,
            ContractJsonParseTest
                    .jsonFileLocation(contractBaseDir, contractName, inputFileName),
            "-p", packageName,
            "-o", tempDirPath
    ).toArray(new String[0]));

    verifyGeneratedCode(tempDirPath + File.separator
            + packageName.replace('.', File.separatorChar) + File.separator
            + Strings.capitaliseFirstLetter(inputFileName) + ".java");
}
 
Example #3
Source File: SolidityFunctionWrapperGeneratorTest.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
private void testCodeGeneration(
        String contractName, String inputFileName, String packageName, String types)
        throws Exception {

    SolidityFunctionWrapperGenerator.main(Arrays.asList(
            types,
            solidityBaseDir + File.separator + contractName + File.separator
                    + "build" + File.separator + inputFileName + ".bin",
            solidityBaseDir + File.separator + contractName + File.separator
                    + "build" + File.separator + inputFileName + ".abi",
            "-p", packageName,
            "-o", tempDirPath
    ).toArray(new String[0])); // https://shipilev.net/blog/2016/arrays-wisdom-ancients/

    verifyGeneratedCode(tempDirPath + File.separator
            + packageName.replace('.', File.separatorChar) + File.separator
            + Strings.capitaliseFirstLetter(inputFileName) + ".java");
}
 
Example #4
Source File: SolidityFunctionWrapper.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
MethodSpec buildDefaultEventObservableFunction(
        String responseClassName,
        String functionName) {

    String generatedFunctionName =
            Strings.lowercaseFirstLetter(functionName) + "EventObservable";
    ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(ClassName.get(rx
            .Observable.class), ClassName.get("", responseClassName));

    MethodSpec.Builder observableMethodBuilder =
            MethodSpec.methodBuilder(generatedFunctionName)
                    .addModifiers(Modifier.PUBLIC)
                    .addParameter(DefaultBlockParameter.class, START_BLOCK)
                    .addParameter(DefaultBlockParameter.class, END_BLOCK)
                    .returns(parameterizedTypeName);

    observableMethodBuilder.addStatement("$1T filter = new $1T($2L, $3L, "
            + "getContractAddress())", PlatonFilter.class, START_BLOCK, END_BLOCK)
            .addStatement("filter.addSingleTopic($T.encode("
                    + buildEventDefinitionName(functionName) + "))", EventEncoder.class)
            .addStatement("return " + generatedFunctionName + "(filter)");

    return observableMethodBuilder
            .build();
}
 
Example #5
Source File: SolidityFunctionWrapper.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
MethodSpec buildDefaultEventObservableFunction(
        String responseClassName,
        String functionName) {

    String generatedFunctionName =
            Strings.lowercaseFirstLetter(functionName) + "EventObservable";
    ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(ClassName.get(rx
            .Observable.class), ClassName.get("", responseClassName));

    MethodSpec.Builder observableMethodBuilder =
            MethodSpec.methodBuilder(generatedFunctionName)
                    .addModifiers(Modifier.PUBLIC)
                    .addParameter(DefaultBlockParameter.class, START_BLOCK)
                    .addParameter(DefaultBlockParameter.class, END_BLOCK)
                    .returns(parameterizedTypeName);

    observableMethodBuilder.addStatement("$1T filter = new $1T($2L, $3L, "
            + "getContractAddress())", EthFilter.class, START_BLOCK, END_BLOCK)
            .addStatement("filter.addSingleTopic($T.encode("
                    + buildEventDefinitionName(functionName) + "))", EventEncoder.class)
            .addStatement("return " + generatedFunctionName + "(filter)");

    return observableMethodBuilder
            .build();
}
 
Example #6
Source File: WasmFunctionWrapper.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
MethodSpec buildDefaultEventObservableFunction(String responseClassName, String functionName) {

		String generatedFunctionName = Strings.lowercaseFirstLetter(functionName) + "EventObservable";
		ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(ClassName.get(rx.Observable.class),
				ClassName.get("", responseClassName));

		MethodSpec.Builder observableMethodBuilder = MethodSpec.methodBuilder(generatedFunctionName).addModifiers(Modifier.PUBLIC)
				.addParameter(DefaultBlockParameter.class, START_BLOCK).addParameter(DefaultBlockParameter.class, END_BLOCK)
				.returns(parameterizedTypeName);

		observableMethodBuilder.addStatement("$1T filter = new $1T($2L, $3L, " + "getContractAddress())", PlatonFilter.class, START_BLOCK, END_BLOCK)
				.addStatement("filter.addSingleTopic($T.encode(" + buildEventDefinitionName(functionName) + "))", WasmEventEncoder.class)
				.addStatement("return " + generatedFunctionName + "(filter)");

		return observableMethodBuilder.build();
	}
 
Example #7
Source File: WasmFunctionWrapper.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
MethodSpec buildEventObservableFunction(String responseClassName, String functionName, List<NamedTypeName> indexedParameters,
		List<NamedTypeName> nonIndexedParameters) {

	String generatedFunctionName = Strings.lowercaseFirstLetter(functionName) + "EventObservable";
	ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(ClassName.get(rx.Observable.class),
			ClassName.get("", responseClassName));

	MethodSpec.Builder observableMethodBuilder = MethodSpec.methodBuilder(generatedFunctionName).addModifiers(Modifier.PUBLIC)
			.addParameter(PlatonFilter.class, FILTER).returns(parameterizedTypeName);

	TypeSpec converter = TypeSpec.anonymousClassBuilder("")
			.addSuperinterface(
					ParameterizedTypeName.get(ClassName.get(Func1.class), ClassName.get(Log.class), ClassName.get("", responseClassName)))
			.addMethod(MethodSpec.methodBuilder("call").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).addParameter(Log.class, "log")
					.returns(ClassName.get("", responseClassName))
					.addStatement("$T eventValues = extractEventParametersWithLog(" + buildEventDefinitionName(functionName) + ", log)",
							WasmContract.WasmEventValuesWithLog.class)
					.addStatement("$1T typedResponse = new $1T()", ClassName.get("", responseClassName))
					.addCode(buildTypedResponse("typedResponse", indexedParameters, nonIndexedParameters, true))
					.addStatement("return typedResponse").build())
			.build();

	observableMethodBuilder.addStatement("return web3j.platonLogObservable(filter).map($L)", converter);

	return observableMethodBuilder.build();
}
 
Example #8
Source File: WasmFunctionWrapper.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
MethodSpec buildEventTransactionReceiptFunction(String responseClassName, String functionName, List<NamedTypeName> indexedParameters,
		List<NamedTypeName> nonIndexedParameters) {

	ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(ClassName.get(List.class), ClassName.get("", responseClassName));

	String generatedFunctionName = "get" + Strings.capitaliseFirstLetter(functionName) + "Events";
	MethodSpec.Builder transactionMethodBuilder = MethodSpec.methodBuilder(generatedFunctionName).addModifiers(Modifier.PUBLIC)
			.addParameter(TransactionReceipt.class, "transactionReceipt").returns(parameterizedTypeName);

	transactionMethodBuilder
			.addStatement("$T valueList = extractEventParametersWithLog(" + buildEventDefinitionName(functionName) + ", " + "transactionReceipt)",
					ParameterizedTypeName.get(List.class, WasmContract.WasmEventValuesWithLog.class))
			.addStatement("$1T responses = new $1T(valueList.size())",
					ParameterizedTypeName.get(ClassName.get(ArrayList.class), ClassName.get("", responseClassName)))
			.beginControlFlow("for ($T eventValues : valueList)", WasmContract.WasmEventValuesWithLog.class)
			.addStatement("$1T typedResponse = new $1T()", ClassName.get("", responseClassName))
			.addCode(buildTypedResponse("typedResponse", indexedParameters, nonIndexedParameters, false))
			.addStatement("responses.add(typedResponse)").endControlFlow();

	transactionMethodBuilder.addStatement("return responses");
	return transactionMethodBuilder.build();
}
 
Example #9
Source File: TruffleJsonFunctionWrapperGeneratorTest.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
private void testCodeGeneration(
        String contractName, String inputFileName, String packageName, String types)
        throws Exception {

    TruffleJsonFunctionWrapperGenerator.main(Arrays.asList(
            types,
            ContractJsonParseTest
                    .jsonFileLocation(contractBaseDir, contractName, inputFileName),
            "-p", packageName,
            "-o", tempDirPath
    ).toArray(new String[0]));

    verifyGeneratedCode(tempDirPath + File.separator
            + packageName.replace('.', File.separatorChar) + File.separator
            + Strings.capitaliseFirstLetter(inputFileName) + ".java");
}
 
Example #10
Source File: WasmFunctionWrapper.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
public TypeSpec buildStruct(WasmAbiDefinition functionDefinition, Set<String> customTypes) {
	String className = Strings.capitaliseFirstLetter(functionDefinition.getName());
	TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC, Modifier.STATIC);
	List<FieldSpec> fieldSpecs = new ArrayList<>();

	if (null != functionDefinition.getBaseclass() && !functionDefinition.getBaseclass().isEmpty()) {
		String baseClass = Strings.capitaliseFirstLetter(functionDefinition.getBaseclass().get(0));
		FieldSpec field = FieldSpec.builder(ClassName.get("", baseClass), "baseClass", Modifier.PUBLIC).build();
		fieldSpecs.add(field);
	}
	for (int i = 0; i < functionDefinition.getFields().size(); i++) {
		WasmAbiDefinition.NamedType namedType = functionDefinition.getFields().get(i);
		String name = namedType.getName();
		String type = namedType.getType();
		fieldSpecs.add(FieldSpec.builder(buildTypeName(type, customTypes), name, Modifier.PUBLIC).build());
	}
	typeBuilder.addFields(fieldSpecs);

	return typeBuilder.build();
}
 
Example #11
Source File: SolidityFunctionWrapperGeneratorTest.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
private void testCodeGeneration(
        String contractName, String inputFileName, String packageName, String types)
        throws Exception {

    SolidityFunctionWrapperGenerator.main(Arrays.asList(
            types,
            solidityBaseDir + File.separator + contractName + File.separator
                    + "build" + File.separator + inputFileName + ".bin",
            solidityBaseDir + File.separator + contractName + File.separator
                    + "build" + File.separator + inputFileName + ".abi",
            "-p", packageName,
            "-o", tempDirPath
    ).toArray(new String[0])); // https://shipilev.net/blog/2016/arrays-wisdom-ancients/

    verifyGeneratedCode(tempDirPath + File.separator
            + packageName.replace('.', File.separatorChar) + File.separator
            + Strings.capitaliseFirstLetter(inputFileName) + ".java");
}
 
Example #12
Source File: SolidityFunctionWrapper.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
void generateJavaFiles(
        String contractName, String bin, List<AbiDefinition> abi, String destinationDir,
        String basePackageName, Map<String, String> addresses)
        throws IOException, ClassNotFoundException {
    String className = Strings.capitaliseFirstLetter(contractName);

    TypeSpec.Builder classBuilder = createClassBuilder(className, bin);

    classBuilder.addMethod(buildConstructor(Credentials.class, CREDENTIALS));
    classBuilder.addMethod(buildConstructor(TransactionManager.class,
            TRANSACTION_MANAGER));
    classBuilder.addMethods(
            buildFunctionDefinitions(className, classBuilder, abi));
    classBuilder.addMethod(buildLoad(className, Credentials.class, CREDENTIALS));
    classBuilder.addMethod(buildLoad(className, TransactionManager.class,
            TRANSACTION_MANAGER));

    addAddressesSupport(classBuilder, addresses);

    write(basePackageName, classBuilder.build(), destinationDir);
}
 
Example #13
Source File: TruffleJsonFunctionWrapperGeneratorTest.java    From web3j with Apache License 2.0 6 votes vote down vote up
private void testCodeGeneration(
        String contractName, String inputFileName, String packageName, String types)
        throws Exception {

    TruffleJsonFunctionWrapperGenerator.main(
            Arrays.asList(
                            types,
                            ContractJsonParseTest.jsonFileLocation(
                                    contractBaseDir, contractName, inputFileName),
                            "-p",
                            packageName,
                            "-o",
                            tempDirPath)
                    .toArray(new String[0]));

    verifyGeneratedCode(
            tempDirPath
                    + File.separator
                    + packageName.replace('.', File.separatorChar)
                    + File.separator
                    + Strings.capitaliseFirstLetter(inputFileName)
                    + ".java");
}
 
Example #14
Source File: SolidityFunctionWrapper.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
MethodSpec buildEventTransactionReceiptFunction(
        String responseClassName,
        String functionName,
        List<NamedTypeName> indexedParameters,
        List<NamedTypeName> nonIndexedParameters) {

    ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(
            ClassName.get(List.class), ClassName.get("", responseClassName));

    String generatedFunctionName = "get" + Strings.capitaliseFirstLetter(functionName)
            + "Events";
    MethodSpec.Builder transactionMethodBuilder = MethodSpec
            .methodBuilder(generatedFunctionName)
            .addModifiers(Modifier.PUBLIC)
            .addParameter(TransactionReceipt.class, "transactionReceipt")
            .returns(parameterizedTypeName);

    transactionMethodBuilder.addStatement("$T valueList = extractEventParametersWithLog("
            + buildEventDefinitionName(functionName) + ", "
            + "transactionReceipt)", ParameterizedTypeName.get(List.class,
                    Contract.EventValuesWithLog.class))
            .addStatement("$1T responses = new $1T(valueList.size())",
                    ParameterizedTypeName.get(ClassName.get(ArrayList.class),
                            ClassName.get("", responseClassName)))
            .beginControlFlow("for ($T eventValues : valueList)",
                    Contract.EventValuesWithLog.class)
            .addStatement("$1T typedResponse = new $1T()",
                    ClassName.get("", responseClassName))
            .addCode(buildTypedResponse("typedResponse", indexedParameters,
                    nonIndexedParameters, false))
            .addStatement("responses.add(typedResponse)")
            .endControlFlow();


    transactionMethodBuilder.addStatement("return responses");
    return transactionMethodBuilder.build();
}
 
Example #15
Source File: FunctionReturnDecoder.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Decode ABI encoded return values from smart contract function call.
 *
 * @param rawInput ABI encoded input
 * @param outputParameters list of return types as {@link TypeReference}
 * @return {@link List} of values returned by function, {@link Collections#emptyList()} if
 *         invalid response
 */
public static List<Type> decode(
        String rawInput, List<TypeReference<Type>> outputParameters) {
    String input = Numeric.cleanHexPrefix(rawInput);

    if (Strings.isEmpty(input)) {
        return Collections.emptyList();
    } else {
        return build(input, outputParameters);
    }
}
 
Example #16
Source File: SolidityFunctionWrapperGenerator.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private void generate() throws IOException, ClassNotFoundException {

        File binaryFile = new File(binaryFileLocation);
        if (!binaryFile.exists()) {
            exitError("Invalid input binary file specified: " + binaryFileLocation);
        }

        byte[] bytes = Files.readBytes(new File(binaryFile.toURI()));
        String binary = new String(bytes);

        File absFile = new File(absFileLocation);
        if (!absFile.exists() || !absFile.canRead()) {
            exitError("Invalid input ABI file specified: " + absFileLocation);
        }
        String fileName = absFile.getName();
        String contractName = getFileNameNoExtension(fileName);
        bytes = Files.readBytes(new File(absFile.toURI()));
        String abi = new String(bytes);

        List<AbiDefinition> functionDefinitions = loadContractDefinition(absFile);

        if (functionDefinitions.isEmpty()) {
            exitError("Unable to parse input ABI file");
        } else {
            String className = Strings.capitaliseFirstLetter(contractName);
            System.out.printf("Generating " + basePackageName + "." + className + " ... ");
            new SolidityFunctionWrapper(useJavaNativeTypes).generateJavaFiles(
                    contractName, binary, abi, destinationDirLocation.toString(), basePackageName);
            System.out.println("File written to " + destinationDirLocation.toString() + "\n");
        }
    }
 
Example #17
Source File: TruffleJsonFunctionWrapperGenerator.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        String[] fullArgs;
        if (args.length == 5) {
            fullArgs = new String[args.length + 1];
            fullArgs[0] = JAVA_TYPES_ARG;
            System.arraycopy(args, 0, fullArgs, 1, args.length);
        } else {
            fullArgs = args;
        }

        if (fullArgs.length != 6) {
            exitError(USAGE);
        }

        boolean useJavaNativeTypes = useJavaNativeTypes(fullArgs[0], USAGE);

        String jsonFileLocation = parsePositionalArg(fullArgs, 1);
        String destinationDirLocation = parseParameterArgument(fullArgs, "-o", "--outputDir");
        String basePackageName = parseParameterArgument(fullArgs, "-p", "--package");

        if (Strings.isEmpty(jsonFileLocation)
                || Strings.isEmpty(destinationDirLocation)
                || Strings.isEmpty(basePackageName)) {
            exitError(USAGE);
        }

        new TruffleJsonFunctionWrapperGenerator(
                jsonFileLocation,
                destinationDirLocation,
                basePackageName,
                useJavaNativeTypes)
                .generate();
    }
 
Example #18
Source File: TruffleJsonFunctionWrapperGenerator.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void generate() throws IOException, ClassNotFoundException {

    File truffleJsonFile = new File(jsonFileLocation);
    if (!truffleJsonFile.exists() || !truffleJsonFile.canRead()) {
        exitError("Invalid input json file specified: " + jsonFileLocation);
    }

    String fileName = truffleJsonFile.getName();
    String contractName = getFileNameNoExtension(fileName);

    Contract c = loadContractDefinition(truffleJsonFile);
    if (c == null) {
        exitError("Unable to parse input json file");
    } else {
        String className = Strings.capitaliseFirstLetter(contractName);
        System.out.printf("Generating " + basePackageName + "." + className + " ... ");
        Map<String, String> addresses;
        if (c.networks != null && !c.networks.isEmpty()) {
            addresses = c.networks.entrySet().stream()
                    .filter(e -> (e.getValue() != null && e.getValue().getAddress() != null))
                    .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().getAddress()
                    ));
        } else {
            addresses = Collections.EMPTY_MAP;
        }
        new SolidityFunctionWrapper(useJavaNativeTypes)
                .generateJavaFiles(contractName,
                        c.getBytecode(),
                        c.getAbi(),
                        destinationDirLocation.toString(),
                        basePackageName,
                        addresses);
        System.out.println("File written to " + destinationDirLocation.toString() + "\n");
    }
}
 
Example #19
Source File: TupleGenerator.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private MethodSpec generateEqualsSpec(String className, int size) {
    MethodSpec.Builder equalsSpecBuilder = MethodSpec.methodBuilder("equals")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .addParameter(Object.class, "o")
            .returns(boolean.class)
            .beginControlFlow("if (this == o)")
            .addStatement("return true")
            .endControlFlow()
            .beginControlFlow("if (o == null || getClass() != o.getClass())")
            .addStatement("return false")
            .endControlFlow();

    String typeParams = Strings.repeat('?', size).replaceAll("\\?", "?, ");
    typeParams = typeParams.substring(0, typeParams.length() - 2);
    String wildcardClassName = className + "<" + typeParams + ">";

    String name = "tuple" + size;
    equalsSpecBuilder
            .addStatement("$L $L = ($L) o", wildcardClassName, name, wildcardClassName);

    for (int i = 1; i < size; i++) {
        String value = VALUE + i;

        equalsSpecBuilder.beginControlFlow(
                "if ($L != null ? !$L.equals($L.$L) : $L.$L != null)",
                value, value, name, value, name, value)
                .addStatement("return false")
                .endControlFlow();
    }

    String lastValue = VALUE + size;
    equalsSpecBuilder
            .addStatement("return $L != null ? $L.equals($L.$L) : $L.$L == null",
                    lastValue, lastValue, name, lastValue, name, lastValue);

    return equalsSpecBuilder.build();
}
 
Example #20
Source File: DefaultFunctionReturnDecoder.java    From web3j with Apache License 2.0 5 votes vote down vote up
public List<Type> decodeFunctionResult(
        String rawInput, List<TypeReference<Type>> outputParameters) {

    String input = Numeric.cleanHexPrefix(rawInput);

    if (Strings.isEmpty(input)) {
        return Collections.emptyList();
    } else {
        return build(input, outputParameters);
    }
}
 
Example #21
Source File: Keys.java    From web3j with Apache License 2.0 5 votes vote down vote up
public static String getAddress(String publicKey) {
    String publicKeyNoPrefix = Numeric.cleanHexPrefix(publicKey);

    if (publicKeyNoPrefix.length() < PUBLIC_KEY_LENGTH_IN_HEX) {
        publicKeyNoPrefix =
                Strings.zeros(PUBLIC_KEY_LENGTH_IN_HEX - publicKeyNoPrefix.length())
                        + publicKeyNoPrefix;
    }
    String hash = Hash.sha3(publicKeyNoPrefix);
    return hash.substring(hash.length() - ADDRESS_LENGTH_IN_HEX); // right most 160 bits
}
 
Example #22
Source File: KeysTest.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAddressZeroPadded() {
    byte[] address =
            Keys.getAddress(
                    Numeric.toBytesPadded(BigInteger.valueOf(0x1234), Keys.PUBLIC_KEY_SIZE));
    String expected = Numeric.toHexStringNoPrefix(address);

    String value = "1234";
    assertEquals(
            Keys.getAddress(
                    "0x"
                            + Strings.zeros(Keys.PUBLIC_KEY_LENGTH_IN_HEX - value.length())
                            + value),
            (expected));
}
 
Example #23
Source File: SolidityFunctionWrapperGenerator.java    From web3j with Apache License 2.0 5 votes vote down vote up
public final void generate() throws IOException, ClassNotFoundException {
    String binary = Contract.BIN_NOT_PROVIDED;
    if (binFile != null) {
        byte[] bytes = Files.readBytes(binFile);
        binary = new String(bytes);
    }
    List<AbiDefinition> functionDefinitions = loadContractDefinition(abiFile);

    if (functionDefinitions.isEmpty()) {
        exitError("Unable to parse input ABI file");
    } else {
        String className = Strings.capitaliseFirstLetter(contractName);
        System.out.print("Generating " + basePackageName + "." + className + " ... ");

        new SolidityFunctionWrapper(
                        useJavaNativeTypes,
                        useJavaPrimitiveTypes,
                        generateSendTxForCalls,
                        addressLength)
                .generateJavaFiles(
                        contractClass,
                        contractName,
                        binary,
                        functionDefinitions,
                        destinationDirLocation.toString(),
                        basePackageName,
                        null);

        System.out.println("File written to " + destinationDirLocation.toString() + "\n");
    }
}
 
Example #24
Source File: SolidityFunctionWrapper.java    From web3j with Apache License 2.0 5 votes vote down vote up
MethodSpec buildDefaultEventFlowableFunction(String responseClassName, String functionName) {

        String generatedFunctionName = Strings.lowercaseFirstLetter(functionName) + "EventFlowable";
        ParameterizedTypeName parameterizedTypeName =
                ParameterizedTypeName.get(
                        ClassName.get(Flowable.class), ClassName.get("", responseClassName));

        MethodSpec.Builder flowableMethodBuilder =
                MethodSpec.methodBuilder(generatedFunctionName)
                        .addModifiers(Modifier.PUBLIC)
                        .addParameter(DefaultBlockParameter.class, START_BLOCK)
                        .addParameter(DefaultBlockParameter.class, END_BLOCK)
                        .returns(parameterizedTypeName);

        flowableMethodBuilder
                .addStatement(
                        "$1T filter = new $1T($2L, $3L, " + "getContractAddress())",
                        EthFilter.class,
                        START_BLOCK,
                        END_BLOCK)
                .addStatement(
                        "filter.addSingleTopic($T.encode("
                                + buildEventDefinitionName(functionName)
                                + "))",
                        EventEncoder.class)
                .addStatement("return " + generatedFunctionName + "(filter)");

        return flowableMethodBuilder.build();
    }
 
Example #25
Source File: TruffleJsonFunctionWrapperGenerator.java    From web3j with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        String[] fullArgs;
        if (args.length == 5) {
            fullArgs = new String[args.length + 1];
            fullArgs[0] = JAVA_TYPES_ARG;
            System.arraycopy(args, 0, fullArgs, 1, args.length);
        } else {
            fullArgs = args;
        }

        if (fullArgs.length != 6) {
            exitError(USAGE);
        }

        boolean useJavaNativeTypes = useJavaNativeTypes(fullArgs[0], USAGE);

        String jsonFileLocation = parsePositionalArg(fullArgs, 1);
        String destinationDirLocation = parseParameterArgument(fullArgs, "-o", "--outputDir");
        String basePackageName = parseParameterArgument(fullArgs, "-p", "--package");

        if (Strings.isEmpty(jsonFileLocation)
                || Strings.isEmpty(destinationDirLocation)
                || Strings.isEmpty(basePackageName)) {
            exitError(USAGE);
        }

        new TruffleJsonFunctionWrapperGenerator(
                        jsonFileLocation,
                        destinationDirLocation,
                        basePackageName,
                        useJavaNativeTypes)
                .generate();
    }
 
Example #26
Source File: Keys.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
public static String getAddress(String publicKey) {
    String publicKeyNoPrefix = Numeric.cleanHexPrefix(publicKey);

    if (publicKeyNoPrefix.length() < PUBLIC_KEY_LENGTH_IN_HEX) {
        publicKeyNoPrefix = Strings.zeros(
                PUBLIC_KEY_LENGTH_IN_HEX - publicKeyNoPrefix.length())
                + publicKeyNoPrefix;
    }
    String hash = Hash.sha3(publicKeyNoPrefix);
    return hash.substring(hash.length() - ADDRESS_LENGTH_IN_HEX);  // right most 160 bits
}
 
Example #27
Source File: Keys.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
public static String getAddress(String publicKey) {
    String publicKeyNoPrefix = Numeric.cleanHexPrefix(publicKey);

    if (publicKeyNoPrefix.length() < PUBLIC_KEY_LENGTH_IN_HEX) {
        publicKeyNoPrefix = Strings.zeros(
                PUBLIC_KEY_LENGTH_IN_HEX - publicKeyNoPrefix.length())
                + publicKeyNoPrefix;
    }
    String hash = Hash.sha3(publicKeyNoPrefix);
    return hash.substring(hash.length() - ADDRESS_LENGTH_IN_HEX);  // right most 160 bits
}
 
Example #28
Source File: KeysTest.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAddressZeroPadded() {
    byte[] address = Keys.getAddress(
            Numeric.toBytesPadded(BigInteger.valueOf(0x1234), Keys.PUBLIC_KEY_SIZE));
    String expected = Numeric.toHexStringNoPrefix(address);

    String value = "1234";
    assertThat(Keys.getAddress("0x"
                    + Strings.zeros(Keys.PUBLIC_KEY_LENGTH_IN_HEX - value.length()) + value),
            equalTo(expected));
}
 
Example #29
Source File: SolidityFunctionWrapperGenerator.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
private void generate() throws IOException, ClassNotFoundException {

		File binaryFile = new File(binaryFileLocation);
		if (!binaryFile.exists()) {
			exitError("Invalid input binary file specified: " + binaryFileLocation);
		}

		byte[] bytes = Files.readBytes(new File(binaryFile.toURI()));
		String binary = new String(bytes);

		File absFile = new File(absFileLocation);
		if (!absFile.exists() || !absFile.canRead()) {
			exitError("Invalid input ABI file specified: " + absFileLocation);
		}
		String fileName = absFile.getName();
		String contractName = getFileNameNoExtension(fileName);
		bytes = Files.readBytes(new File(absFile.toURI()));
		String abi = new String(bytes);

		List<AbiDefinition> functionDefinitions = loadContractDefinition(absFile);

		if (functionDefinitions.isEmpty()) {
			exitError("Unable to parse input ABI file");
		} else {
			String className = Strings.capitaliseFirstLetter(contractName);
			System.out.printf("Generating " + basePackageName + "." + className + " ... ");
			new SolidityFunctionWrapper(useJavaNativeTypes).generateJavaFiles(contractName, binary, abi, destinationDirLocation.toString(),
					basePackageName);
			System.out.println("File written to " + destinationDirLocation.toString() + "\n");
		}
	}
 
Example #30
Source File: WasmFunctionWrapper.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
List<MethodSpec> buildEventFunctions(WasmAbiDefinition functionDefinition, TypeSpec.Builder classBuilder, Set<String> customTypes) {
	String functionName = functionDefinition.getName();
	String responseClassName = Strings.capitaliseFirstLetter(functionName) + "EventResponse";

	List<NamedType> inputs = functionDefinition.getInput();
	int topic = functionDefinition.getTopic();
	List<NamedTypeName> indexedParameters = new ArrayList<>();
	List<NamedTypeName> nonIndexedParameters = new ArrayList<>();
	for (int i = 0; i < inputs.size(); i++) {
		NamedType namedType = inputs.get(i);
		String name = namedType.getName();
		String type = namedType.getType();

		TypeName typeName = buildTypeName(type, customTypes);
		boolean indexed = i < topic ? true : false;
		NamedTypeName parameter = new NamedTypeName(name, typeName, indexed);
		if (indexed) {
			indexedParameters.add(parameter);
		} else {
			nonIndexedParameters.add(parameter);
		}
	}

	classBuilder.addField(createEventDefinition(functionName, indexedParameters, nonIndexedParameters));
	classBuilder.addType(buildEventResponseObject(responseClassName, indexedParameters, nonIndexedParameters));

	List<MethodSpec> methods = new ArrayList<>();
	methods.add(buildEventTransactionReceiptFunction(responseClassName, functionName, indexedParameters, nonIndexedParameters));
	methods.add(buildEventObservableFunction(responseClassName, functionName, indexedParameters, nonIndexedParameters));
	methods.add(buildDefaultEventObservableFunction(responseClassName, functionName));
	return methods;
}