以太坊常见问题和错误

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

怎样在android中用web3j查询账户状态?

我按照官网的文件说明查询一个智能合约的情况。但我得不到想要的结果,这是我的代码:

 Web3j web3j = Web3jFactory.build(new HttpService(url));
                List<Type> inputParameters = new ArrayList<>();
                List<TypeReference<?>> outputParameters = new ArrayList<>();
                Function function = new Function("getManufacturer",
                        inputParameters,
                        outputParameters);
                String functionEncoder = FunctionEncoder.encode(function);
                EthCall response = web3j.ethCall(
                        Transaction.createEthCallTransaction(contractAddress,
                        DefaultBlockParameterName.LATEST
                ).sendAsync().get();
                List<Type> someType = FunctionReturnDecoder.decode(response.getValue(),function.getOutputParameters());
                Iterator<Type> it = someType.iterator();
                Type resault = someType.get(0);
                String a = resault.toString();
                Log.d("MainActitity", a + "111");

问题解答

web3j是很不错的,不过需要多一点练习,你会发现它是一个很棒的通过java开发以太坊的API:

代码有2个问题: 1.问题在代码中的第三行。列表outputParameters应该包含方法的所有返回变量。所以,如果你希望得到一个字符串,你应该这么写:

Arrays.asList(new TypeReference< Utf8String>() {})

2.但是,可能会有更有趣的发现,你甚至不必担心编写Java代码来实现你的solidity功能,因为web3j可以做到这一点。SolidityFunctionWrapperGenerator为你生成这些文件。你所需要的智能合约的.bin和.abi,它们生成一个Java类。你可以用地址、web3j实例和Credentials.java来实例化该类。这样,你就可以调用区块链中的智能合约的方法,就像使用其他Java类一样。。